SlideShare a Scribd company logo
Scala.compareTo(Java)
to try or not to try?
Based on
http://github.com/jamie-allen/taxonomy-of-scala
by Jamie Allen
Quick Start
Download Scala from :
- http://www.scala-lang.org/downloads
Download Eclipse with Scala Worksheet :
- http://typesafe.com/stack/scala_ide_download
Download SBT (Simple Build Tool):
- http://twitter.github.com/scala_school/sbt.html
SBT - Simple Build Tool
SBT is a simple build tool, similar to maven.
Helps you create, build, test, package your
scala application. It includes dependency
management which is defined in regular
Scala file, allow to define simple build-
plugins - everything simple and extensible
and XML free.
Main concepts of Scala:
- runs on JVM
- statically typed
- compiled into bytecode
- Advanced type system with type inference
and declaration-site variance
- Function types (including anonymous)
which support closures
- Pattern-matching
- Implicit parameters and conversions
- Full interoperability with Java
Let's start!
Create file hello.scala
object HelloWorld extends App {
println("Hello, World!")
}
Compile it :
>scalac hello.scala
Run it :)
>scala HelloWorld
"Hello, WOrld!"
- file can have whatever name
- no semicolons
- simplified syntax for many common cases
More Java-like version of previous example
(with main method):
object HelloWorld2 {
def main(args:Array[String])={
println("Hello 2")
}
}
What is going on?
Case Classes
case class Person(firstName: String = "Jamie",
lastName: String = "Allen")
val jamieDoe = Person(lastName = "Doe")
res0: Person = Person(Jamie,Doe)
● Data Transfer Objects (DTOs) done right
● By default, class arguments are immutable & public
● Should never be extended
● Provide equals(), copy(), hashCode() and toString()
implementations
● Don’t have to use new keyword to create instances
● Named Parameters and Default arguments give us
Builder pattern semantics
Lazy Definitions
lazy val calculatedValue = piToOneMillionDecimalPoints()
● Excellent for deferring expensive operations until they
are needed
● Reducing initial footprint
● Resolving ordering issues
● Implemented with a guard field and synchronization,
ensuring it is created when necessary
Imports
import scala.collection.immutable.Map
class Person(val fName: String, val lName: String) {
import scala.collection.mutable.{Map => MMap}
val cars: MMap[String, String] = MMap()
...
}
● Can be anywhere in a class
● Allow for selecting multiple classes from a package or
using wildcards
● Aliasing
● Order matters!
Objects
object Bootstrapper extends App { Person.createJamieAllen
}
object Person {
def createJamieAllen = new Person("Jamie", "Allen")
def createJamieDoe = new Person("Jamie", "Doe")
val aConstantValue = "A constant value”
}
class Person(val firstName: String, val lastName: String)
● Singletons within a JVM process
● No private constructor histrionics
● Companion Objects, used for factories and constants
The apply() method
Array(1, 2, 3)
res0: Array[Int] = Array(1, 2, 3)
res0(1)
res1: Int = 2
● In companion objects, it defines default behavior if no
method is called on it
● In a class, it defines the same thing on an instance of
the class
Tuples
def firstPerson = (1, Person(firstName = “Barbara”))
val (num: Int, person: Person) = firstPerson
● Binds you to an implementation
● Great way to group values without a DTO
● How to return multiple values, but wrapped in a single
instance that you can bind to specific values
Pattern Matching Examples
name match {
case "Lisa" => println("Found Lisa”)
case Person("Bob") => println("Found Bob”)
case "Karen" | "Michelle" => println("Found Karen or Michelle”)
case Seq("Dave", "John") => println("Got Dave before John”)
case Seq("Dave", "John", _*) => println("Got Dave before John”)
case ("Susan", "Steve") => println("Got Susan and Steve”)
case x: Int if x > 5 => println("got value greater than 5: " + x)
case x => println("Got something that wasn't an Int: " + x)
case _ => println("Not found”)
}
● A gateway drug for Scala
● Extremely powerful and readable
● Not compiled down to lookup/table switch unless you use
the @switch annotation,
Scala Collections
val myMap = Map(1 -> "one", 2 -> "two", 3 -> "three")
val mySet = Set(1, 4, 2, 8)
val myList = List(1, 2, 8, 3, 3, 4)
val myVector = Vector(1, 2, 3...)
● You have the choice of mutable or immutable collection
instances, immutable by default
● Rich implementations, extremely flexible
Rich Collection Functionality
val numbers = 1 to 20 // Range(1, 2, 3, ... 20)
numbers.head // Int = 1
numbers.tail // Range(2, 3, 4, ... 20)
numbers.take(5) // Range(1, 2, 3, 4, 5)
numbers.drop(5) // Range(6, 7, 8, ... 20)
● There are many methods available to you in the Scala
collections library
● Spend 5 minutes every day going over the ScalaDoc for
one collection class
Higher Order Functions
val names = List("Barb", "May", "Jon")
names map(_.toUpperCase)
res0: List[java.lang.String] = List(BARB, MAY, JON)
● Really methods in Scala
● Applying closures to collections
Higher Order Functions
val names = List("Barb", "May", "Jon")
names map(_.toUpperCase)
res0: List[java.lang.String] = List(BARB, MAY, JON)
names flatMap(_.toUpperCase)
res1: List[Char] = List(B, A, R, B, M, A, Y, J, O, N)
names filter (_.contains("a"))
res2: List[java.lang.String] = List(Barb, May)
val numbers = 1 to 20 // Range(1, 2, 3, ... 20)
numbers.groupBy(_ % 3)
res3: Map[Int, IndexedSeq[Int]] = Map(1 -> Vector(1, 4, 7,
10, 13, 16, 19), 2 -> Vector(2, 5, 8, 11, 14, 17, 20), 0 -
> Vector(3, 6, 9, 12, 15, 18))
Partial Functions
class MyActor extends Actor {
def receive = {
case s: String => println("Got a String: " + s)
case i: Int => println("Got an Int: " + i)
case x => println("Got something else: " + x)
}
}
● A simple match without the match keyword
● The receive block in Akka actors is an excellent
example
● Is characterized by what "isDefinedAt" in the case
statements
Currying
def product(i: Int)(j: Int) = i * j
val doubler = product(2)_
doubler(3) // Int = 6
doubler(4) // Int = 8
val tripler = product(3)_
tripler(4) // Int = 12
tripler(5) // Int = 15
● Take a function that takes n parameters as separate argument lists
● “Curry” it to create a new function that only takes one parameter
● Fix on a value and use it to apply a specific implementation of a product
with semantic value
● Have to be defined explicitly as such in Scala
● The _ is what explicitly marks this as curried
Implicit Conversions
case class Person(firstName: String, lastName: String)
implicit def PersonToInt(p: Person) = p.toString.head.
toInt
val me = Person("Jamie", "Allen")
val weird = 1 + me
res0: Int = 81
● Looks for definitions at compile time that will satisfy
type incompatibilities
● Modern IDEs will warn you with an underline when
they are in use
● Limit scope as much as possible (see Josh Suereth's
NE Scala 2011)
Implicit Parameters
def executeFutureWithTimeout(f: Future)(implicit t:
Timeout)
implicit val t: Timeout = Timeout(20, TimeUnit.
MILLISECONDS)
executeFutureWithTimeout(Future {proxy.getCustomer(id)})
● Allow you to define default parameter values that are
only overridden if you do so explicitly
● Handy to avoid code duplication
Usefull resources:
https://www.coursera.org/course/progfun - Lessons and Examples on Coursera
- good staring point!!!
http://twitter.github.com/scala_school/
http://docs.scala-lang.org/tutorials/tour/tour-of-scala.html
http://stackoverflow.com/tags/scala/info
http://docs.scala-lang.org/cheatsheets/ :):)
http://github.com/jamie-allen/taxonomy-of-scala (oryginal content of pres.)
http://www.playframework.com/ - Play Framework!!!

More Related Content

PDF
Scala coated JVM
ODP
PDF
Programming in Scala: Notes
PPTX
PDF
camel-scala.pdf
ODP
Scala Reflection & Runtime MetaProgramming
PDF
Procedure Typing for Scala
PDF
Scala coated JVM
Programming in Scala: Notes
camel-scala.pdf
Scala Reflection & Runtime MetaProgramming
Procedure Typing for Scala

What's hot (19)

ODP
10 Things I Hate About Scala
PPTX
Scala fundamentals
PDF
Scala jargon cheatsheet
PDF
scala
PPT
Scala Talk at FOSDEM 2009
PDF
scalaliftoff2009.pdf
PDF
PDF
Javascript basic course
PDF
ScalaTrainings
PDF
Learning Functional Programming Without Growing a Neckbeard
PDF
Scala cheatsheet
PDF
Pragmatic Real-World Scala (short version)
ODP
A Tour Of Scala
PDF
Workshop Scala
PDF
Programming Android Application in Scala.
PDF
Getting Started With Scala
PDF
An Introduction to Scala for Java Developers
PDF
Twins: Object Oriented Programming and Functional Programming
PDF
Metaprogramming in Scala 2.10, Eugene Burmako,
10 Things I Hate About Scala
Scala fundamentals
Scala jargon cheatsheet
scala
Scala Talk at FOSDEM 2009
scalaliftoff2009.pdf
Javascript basic course
ScalaTrainings
Learning Functional Programming Without Growing a Neckbeard
Scala cheatsheet
Pragmatic Real-World Scala (short version)
A Tour Of Scala
Workshop Scala
Programming Android Application in Scala.
Getting Started With Scala
An Introduction to Scala for Java Developers
Twins: Object Oriented Programming and Functional Programming
Metaprogramming in Scala 2.10, Eugene Burmako,
Ad

Viewers also liked (18)

PDF
Using Social Media for Customer Support
PDF
20160629 Habitat Introduction: Austin DevOps/Mesos User Group
PDF
Readership presentation
PDF
Makkers Manifestatie Co-Green
PDF
Healthcare Staffing Services - a Point of View from Dell Healthcare Services
PDF
8th biosimilars congregation 2016
PDF
Social Experience Design
PPTX
Techstars presentation-jonah-lopin-july-2015
PDF
PDF
創新與創業精神個案分享 趨勢科技專家服務
PDF
Tendinte in marketingul digital_2017
PPT
Digitálne chuťovky s ADMA 10.11.2016: Čo sa deje po prezretí videa a banneru?...
PDF
Scaling up key items
PPTX
Kebijakan perikanan indonesia
PPTX
Guía de buenas prácticas para desarrolladores web
PPTX
Estrategias de enseñanza en educación física
PPTX
Plaquette veille brand content 2016
Using Social Media for Customer Support
20160629 Habitat Introduction: Austin DevOps/Mesos User Group
Readership presentation
Makkers Manifestatie Co-Green
Healthcare Staffing Services - a Point of View from Dell Healthcare Services
8th biosimilars congregation 2016
Social Experience Design
Techstars presentation-jonah-lopin-july-2015
創新與創業精神個案分享 趨勢科技專家服務
Tendinte in marketingul digital_2017
Digitálne chuťovky s ADMA 10.11.2016: Čo sa deje po prezretí videa a banneru?...
Scaling up key items
Kebijakan perikanan indonesia
Guía de buenas prácticas para desarrolladores web
Estrategias de enseñanza en educación física
Plaquette veille brand content 2016
Ad

Similar to Scala - core features (20)

PPTX
Taxonomy of Scala
PPTX
Scala, Play 2.0 & Cloud Foundry
PDF
Getting Started With Scala
PDF
Meet scala
PDF
Miles Sabin Introduction To Scala For Java Developers
PDF
A Brief Introduction to Scala for Java Developers
PDF
Getting Started With Scala
PPTX
Scala for curious
PDF
Introduction to Scala
PDF
(How) can we benefit from adopting scala?
PDF
From Java to Scala - advantages and possible risks
PDF
Scala: Object-Oriented Meets Functional, by Iulian Dragos
PDF
Programming in scala - 1
PDF
Scala for Java Developers
PDF
Scala for Java Programmers
PDF
Scala In The Wild
PDF
Scala taxonomy
ODP
Introducing scala
PDF
Introduction to Scala : Clueda
PDF
BCS SPA 2010 - An Introduction to Scala for Java Developers
Taxonomy of Scala
Scala, Play 2.0 & Cloud Foundry
Getting Started With Scala
Meet scala
Miles Sabin Introduction To Scala For Java Developers
A Brief Introduction to Scala for Java Developers
Getting Started With Scala
Scala for curious
Introduction to Scala
(How) can we benefit from adopting scala?
From Java to Scala - advantages and possible risks
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Programming in scala - 1
Scala for Java Developers
Scala for Java Programmers
Scala In The Wild
Scala taxonomy
Introducing scala
Introduction to Scala : Clueda
BCS SPA 2010 - An Introduction to Scala for Java Developers

Scala - core features

  • 1. Scala.compareTo(Java) to try or not to try? Based on http://github.com/jamie-allen/taxonomy-of-scala by Jamie Allen
  • 2. Quick Start Download Scala from : - http://www.scala-lang.org/downloads Download Eclipse with Scala Worksheet : - http://typesafe.com/stack/scala_ide_download Download SBT (Simple Build Tool): - http://twitter.github.com/scala_school/sbt.html
  • 3. SBT - Simple Build Tool SBT is a simple build tool, similar to maven. Helps you create, build, test, package your scala application. It includes dependency management which is defined in regular Scala file, allow to define simple build- plugins - everything simple and extensible and XML free.
  • 4. Main concepts of Scala: - runs on JVM - statically typed - compiled into bytecode - Advanced type system with type inference and declaration-site variance - Function types (including anonymous) which support closures - Pattern-matching - Implicit parameters and conversions - Full interoperability with Java
  • 5. Let's start! Create file hello.scala object HelloWorld extends App { println("Hello, World!") } Compile it : >scalac hello.scala Run it :) >scala HelloWorld "Hello, WOrld!"
  • 6. - file can have whatever name - no semicolons - simplified syntax for many common cases More Java-like version of previous example (with main method): object HelloWorld2 { def main(args:Array[String])={ println("Hello 2") } } What is going on?
  • 7. Case Classes case class Person(firstName: String = "Jamie", lastName: String = "Allen") val jamieDoe = Person(lastName = "Doe") res0: Person = Person(Jamie,Doe) ● Data Transfer Objects (DTOs) done right ● By default, class arguments are immutable & public ● Should never be extended ● Provide equals(), copy(), hashCode() and toString() implementations ● Don’t have to use new keyword to create instances ● Named Parameters and Default arguments give us Builder pattern semantics
  • 8. Lazy Definitions lazy val calculatedValue = piToOneMillionDecimalPoints() ● Excellent for deferring expensive operations until they are needed ● Reducing initial footprint ● Resolving ordering issues ● Implemented with a guard field and synchronization, ensuring it is created when necessary
  • 9. Imports import scala.collection.immutable.Map class Person(val fName: String, val lName: String) { import scala.collection.mutable.{Map => MMap} val cars: MMap[String, String] = MMap() ... } ● Can be anywhere in a class ● Allow for selecting multiple classes from a package or using wildcards ● Aliasing ● Order matters!
  • 10. Objects object Bootstrapper extends App { Person.createJamieAllen } object Person { def createJamieAllen = new Person("Jamie", "Allen") def createJamieDoe = new Person("Jamie", "Doe") val aConstantValue = "A constant value” } class Person(val firstName: String, val lastName: String) ● Singletons within a JVM process ● No private constructor histrionics ● Companion Objects, used for factories and constants
  • 11. The apply() method Array(1, 2, 3) res0: Array[Int] = Array(1, 2, 3) res0(1) res1: Int = 2 ● In companion objects, it defines default behavior if no method is called on it ● In a class, it defines the same thing on an instance of the class
  • 12. Tuples def firstPerson = (1, Person(firstName = “Barbara”)) val (num: Int, person: Person) = firstPerson ● Binds you to an implementation ● Great way to group values without a DTO ● How to return multiple values, but wrapped in a single instance that you can bind to specific values
  • 13. Pattern Matching Examples name match { case "Lisa" => println("Found Lisa”) case Person("Bob") => println("Found Bob”) case "Karen" | "Michelle" => println("Found Karen or Michelle”) case Seq("Dave", "John") => println("Got Dave before John”) case Seq("Dave", "John", _*) => println("Got Dave before John”) case ("Susan", "Steve") => println("Got Susan and Steve”) case x: Int if x > 5 => println("got value greater than 5: " + x) case x => println("Got something that wasn't an Int: " + x) case _ => println("Not found”) } ● A gateway drug for Scala ● Extremely powerful and readable ● Not compiled down to lookup/table switch unless you use the @switch annotation,
  • 14. Scala Collections val myMap = Map(1 -> "one", 2 -> "two", 3 -> "three") val mySet = Set(1, 4, 2, 8) val myList = List(1, 2, 8, 3, 3, 4) val myVector = Vector(1, 2, 3...) ● You have the choice of mutable or immutable collection instances, immutable by default ● Rich implementations, extremely flexible
  • 15. Rich Collection Functionality val numbers = 1 to 20 // Range(1, 2, 3, ... 20) numbers.head // Int = 1 numbers.tail // Range(2, 3, 4, ... 20) numbers.take(5) // Range(1, 2, 3, 4, 5) numbers.drop(5) // Range(6, 7, 8, ... 20) ● There are many methods available to you in the Scala collections library ● Spend 5 minutes every day going over the ScalaDoc for one collection class
  • 16. Higher Order Functions val names = List("Barb", "May", "Jon") names map(_.toUpperCase) res0: List[java.lang.String] = List(BARB, MAY, JON) ● Really methods in Scala ● Applying closures to collections
  • 17. Higher Order Functions val names = List("Barb", "May", "Jon") names map(_.toUpperCase) res0: List[java.lang.String] = List(BARB, MAY, JON) names flatMap(_.toUpperCase) res1: List[Char] = List(B, A, R, B, M, A, Y, J, O, N) names filter (_.contains("a")) res2: List[java.lang.String] = List(Barb, May) val numbers = 1 to 20 // Range(1, 2, 3, ... 20) numbers.groupBy(_ % 3) res3: Map[Int, IndexedSeq[Int]] = Map(1 -> Vector(1, 4, 7, 10, 13, 16, 19), 2 -> Vector(2, 5, 8, 11, 14, 17, 20), 0 - > Vector(3, 6, 9, 12, 15, 18))
  • 18. Partial Functions class MyActor extends Actor { def receive = { case s: String => println("Got a String: " + s) case i: Int => println("Got an Int: " + i) case x => println("Got something else: " + x) } } ● A simple match without the match keyword ● The receive block in Akka actors is an excellent example ● Is characterized by what "isDefinedAt" in the case statements
  • 19. Currying def product(i: Int)(j: Int) = i * j val doubler = product(2)_ doubler(3) // Int = 6 doubler(4) // Int = 8 val tripler = product(3)_ tripler(4) // Int = 12 tripler(5) // Int = 15 ● Take a function that takes n parameters as separate argument lists ● “Curry” it to create a new function that only takes one parameter ● Fix on a value and use it to apply a specific implementation of a product with semantic value ● Have to be defined explicitly as such in Scala ● The _ is what explicitly marks this as curried
  • 20. Implicit Conversions case class Person(firstName: String, lastName: String) implicit def PersonToInt(p: Person) = p.toString.head. toInt val me = Person("Jamie", "Allen") val weird = 1 + me res0: Int = 81 ● Looks for definitions at compile time that will satisfy type incompatibilities ● Modern IDEs will warn you with an underline when they are in use ● Limit scope as much as possible (see Josh Suereth's NE Scala 2011)
  • 21. Implicit Parameters def executeFutureWithTimeout(f: Future)(implicit t: Timeout) implicit val t: Timeout = Timeout(20, TimeUnit. MILLISECONDS) executeFutureWithTimeout(Future {proxy.getCustomer(id)}) ● Allow you to define default parameter values that are only overridden if you do so explicitly ● Handy to avoid code duplication
  • 22. Usefull resources: https://www.coursera.org/course/progfun - Lessons and Examples on Coursera - good staring point!!! http://twitter.github.com/scala_school/ http://docs.scala-lang.org/tutorials/tour/tour-of-scala.html http://stackoverflow.com/tags/scala/info http://docs.scala-lang.org/cheatsheets/ :):) http://github.com/jamie-allen/taxonomy-of-scala (oryginal content of pres.) http://www.playframework.com/ - Play Framework!!!