12. Java: Singletons
public class Singleton {
private Singleton INSTANCE = null;
private Singleton() {}
public Singleton getInstance() {
if (null == INSTANCE) {
INSTANCE = new Singleton()
}
}
13. Objects
class CompanionObjects(val id: Long, val
description: String = "")
object CompanionObjects{
def zero = new CompanionObjects(id = 0,
description = "zero")
def apply(id:Int, description:String)= new
CompanionObjets(id,description)
def one = CompanionObjets(1, "one")
val errorMessage = "ID should be positive"
}
14. Pattern matching
In Java:
Switch statements with String cases have
been implemented in Java SE 7, at least 16
years after they were first requested.
15. Pattern matching
object Matching extends App {
val name :AnyRef= ...
name match {
case "Radim" => println("me")
case "crosby" | "sidney" => println("NHL")
case Seq("sidney", _) => println("sidney with
someone")
case Seq("sidney", _*) => println("sidney with group")
case x: Int if x < 0 => println("negative number")
case y => println("Unknown " + y)
}
}
19. Immutability cont.
val n = "123".reverse
val m = n.reverse
println(n, m) // 321, 123
val o = new StringBuffer("123").reverse()
val p = o.reverse()
println(o, p) // 123, 123
20. Higher order functions
object Collections extends App{
val c = 4 to 8
val s: IndexedSeq[String] = c map(_+"th")
s map (_.toUpperCase)
println(s) //4th, 5th, 6th, 7th, 8th
}
21. Parallel collection
object Parralel extends App{
def time[R](block: => R): R = {
val t0 = System.nanoTime()
val result = block // call-by-name
val t1 = System.nanoTime()
println("Elapsed time: " + (t1 - t0)/1000000 + " ms")
result
}
val c = 1 to 10000000
time { c map (_ + 1) } //4935 ms
time { c.par map (_ + 1) } //3723 ms
}
23. Partial functions
val sample = 1 to 10
val isEven: PartialFunction[Int, String] =
{case x if x % 2 == 0 => x+" is even"}
// the method collect can use isDefinedAt
to select which members to collect
val evenNumbers = sample collect isEven
println(evenNumbers)
25. Futures
import ExecutionContext.Implicits.global
object Futures extends App {
@volatile var totalA = 0
val text = Future {
Thread.sleep(1000); val a = "a" * 16
}
text onSuccess {
case txt => totalA += txt.count(_ == 'a')
}
println(totalA) // 0
Thread.sleep(1000); println(totalA) //0
Thread.sleep(1000); println(totalA) //16
}