3. Scala Conventions
Return is almost optional ; is optional
No args functions doesn’t need ()
def sum(a: Int, b: Int) = a + b def sum(a: Int, b: Int) = {
println(a)
println(b)
a+b
}
def count() = {...}
val cnt = list.count
4. Type Inference
Scala is strongly typed Type is inferred by scala
val a: Int = 1 def funz(a: Int) = a*10.0
def funz2(a: Int):Double = a*10.0
5. Value vs Variable
A value is immutable A variable is mutable
scala val ~= java final attribute
val a = 1
a = 2 // error: reassignment to val
var a = 1
a = 2 // ok
7. Classes
Constructor is class body itself! Costructors override
class Person(name:String) {
var age = 0
println(name)
}
class Person(name:String) {
var age = 0
def this(name:String, anAge:Int) {
this(name)
age = anAge
}
}
8. Case Classes
Equals() and hashcode() are already
implemented!!
case class Color(name:String, code: Int)
val c = Color("red", 34567)
9. Embedded singleton pattern
Scala hasn't static
because Scala is object oriented…. allows you define object
Object and class work togheter
object Obj {
def doSomething() = println
}
Obj.doSomething()
class Color(name:String)
object Color { // this is the singleton
private val colors = Map(
"red" -> new Color("red"),
"green" -> new Color("green"),
"blue" -> new Color("blue"))
def mk(name:String) = colors(name)
}
10. Traits
Similar to interfaces, but much more powerful!
trait Equal {
def isEqual(x: Any): Boolean //Scala allows traits to be partially implemented
def isNotEqual(x: Any): Boolean = !isEqual(x)
}
class Point(xc: Int, yc: Int) extends Equal {
val x = xc
val y = yc
def isEqual(obj: Any) = obj.isInstanceOf[Point] && obj.asInstanceOf[Point].x == x
}
11. Multiple Inheritance
Trait rules
trait Swimming { def swim() = println("I'm swimming") }
abstract class Bird { def fly() = println("I'm flying") }
class Bird1 extends Bird
class Bird2 extends Bird with Swimming
new Bird1().fly() // I'm flying
new Bird2().swim() //I'm swimming
(new Bird1() with Swimming).swim() //composable objects at runtime
13. First class function
def f1(x: Int) = x
def f2(x: Int) = x * 2
def g(f:Int=>Int, x:Int) = f(x) + 1
g(f1, 3) // f1(3) + 1 → 4
g(f2, 3) // f2(3) + 1 → 7
14. Pattern Matching
can match int, string, List, case class!
Match is a function too
case class Color(name: String, code: String)
val obj : Any = _
obj match {
case "string" => println("obj String")
case a: Int => println("obj is Int with value: "+a)
case l: List[_] => println("obj is a List")
case Color(name, code) => println("obj is the color: "+name)
case "string" :: item :: other => println("")
case _ => println("")
}
15. Scala vs Java
def products = orders.flatMap(_.products)
.filter(_.category == category)
val list = List(1,2,3)
public List<Product> getProducts() {
List<Product> products = new ArrayList<Product>();
for(Order order : orders) {
for(Product product : order.getProducts()) {
if(category.equals(product.getCategory())){
products.add(product);
}
}
}
return products;
}
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
16. Scala XML
val foo = <foo>
<bar type="greet">hi</bar>
<bar type="count">1</bar>
<bar type="color">yellow</bar>
</foo>
(foo "bar").map(_ "@type")
18. Scala JS
Scala.js compiles Scala code to JavaScript, allowing you to
write your web application entirely in Scala!
Jquery , AngularJS, NodeJS , etc... are already integrated!
19. Scalable
"Prefer vals, immutable objects,
and methods without side effects.
Reach for them first. Use vars,
mutable objects, and methods with
side effects when you have a
specific need and justification for
them."
Functional is statelessImmutable is stateless
shared or mutable states are scalability killers
Actors react to received messages by
executing a behavior function
Actors never share state and thus
never need to compete for locks for
access to shared data
20. Scala Features
Lazy val
Streams
String interpolation
Runtime code generation
Runtime reflection
Regex
Macros, quasiquotes, sequence comprehension, lambda, currying, tuple...etc.
lazy val funcVal = { println("executing"); 3 }
lazy val fibs = BigInt(0) #:: BigInt(1)
#:: Stream.empty
val str = s"the user ${username} has ${numOfTokens} tokens"
toolbox.eval(toolbox.parse("case class D(a: Int, b: Int)"))
def getTypeTag[T: ru.TypeTag](obj: T) = ru.typeTag[T]
val theType = getTypeTag(List(1,2,3)).tpe
val pattern = "(S|s)cala".r
pattern findFirstIn "Scala is Scalable and cool"