Download presentation
Presentation is loading. Please wait.
Published byEmery Carr Modified over 8 years ago
1
Scala: 6 Silver Bullets Alex Masselot Dev Forum - Vital-IT Tuesday March 9th, 2015
2
Scala: JVM on Steroids
3
Since 2001 (at EPFL)
4
Six Silver Bullets
5
Bullet #1: OO & FP
6
Type Inference val x:Int=10 //explicit val x=10 //implicit Int x=11 //Error var x=10 //mutable x=2.5 //Error
7
Tuples val y=(1, "paf") //Tuple2[Int,String] println(y._2) //paf val (n, s)=y //n=1, s="paf"
8
Class class Peak(val x: Double, val intens: Double) { def times(n:2)=new Peak(x, intens*n) def sqrtIntens = intens * intens lazy val hundred = { new Peak(x, 100 * intens) } override def toString = s"[$x, $intens]” } val p = new Peak(12.34, 100) println(p) //”[12.34, 100]”
9
case class case class Peak(x:Double, intens:Double){ … } val p=Peak(12.34, 100)
10
value class case class RunId(value:Int) extends AnyVal val rid = RunId(42) val x = rid+12 //Error: meaningless
11
Everything is a method val i = 40 val j = i + 2 val k = i.+(2) //strictly equivalent
12
Everything is a method case class Mass(value:Double) extends AnyVal{ def +(m:Mass) = Mass(value+m.value) } case class Peak(x:Mass, intens:Double){ def +(m:Mass) = Peak(x+m, intens) }
13
Hoare’s One Billion Dollar Error null
14
Option[T] Try[T], Future[T] Some[T]NoneSuccess[T]Failure(exc)
15
Singleton: object object Peak{ def apply(m:Double) = Peak(m,0); def readListFromFile(f:File):List[Peak]=… }
16
Trait for Inheritance
17
Functional Programming Functions are First Class Citizens def strangeSum(x:Double, y:Double, f:(Double) => Double) = f(x) + f(y) def square(x:Double) = x*x strangeSum(3, 4, square) // 25
18
Bullet #2: Collections
19
Scala Cookbook – Alvin Alexander
21
Collection List[T] : to be traversed, with head and last direct access, Vector[T] : with random access on integer index, Map[K, V] : for dictionary or hash map structure.
22
val l = List(1,2,3) val l2 = l1 :+ 4 // List(1,2,3,4) val l3 = l1 :: List(5,6,7) // List(1,2,3,4,5,6,7) Adding Values
23
val l = List(1,2,3,4) l(2) // 3 l.head // 1 l.last // 4 l.tail // List(2,3,4) l.take(2) // List(1,2) l.drop(2) // List(3,4) … Accessing
24
val l = List(1,2,3,4) l.map(_ * 10) // List(10,20,30,40) l.find(_%2 == 0) // Some(2) l.filter(_%2 == 0) // List(2,4) l.partition(_%2==0) // (List(2,4), List(1,3)) l.combinations(2) // iterator (1,2), (1,3)... http://www.scala- lang.org/api/current/index.html#scala.collection.immutable.List And (so) much more
25
val l:List[Peak] =... peaks.groupBy(p=>math.floor(p.x)).map({pl => (pl._1, pl._2.map(_.intens).sum) }).toList.sortBy(-_._2).take(2) And compose…
27
And for loops
28
Bullet #3: Pattern Matching
29
def useless(x:Any) = x match{ case x:String => "hello "+x case i:Int if i "small" case i:Int => "large" case _ => "whatever" } A Simple Situation
30
With List @tailrec def biRev(l:List[Int]):List[Int] = l match{ case Nil => List() case x::Nil => List(x) case x1::x2::xs => List(x2, x1):::biRev(xs) } biRev(List(1,2,3,4,5)) //List(2,1,4,3,5)
31
val reMiles="""(\d+)miles""".r val reKm="""(\d+)km""".r def toKm(x:Any):Int = x match{ case x:Int=> x case reMiles(v) => (v.toInt*1.609).toInt case reKm(v) => v.toInt case _ => throw new IllegalArgumentException( s"cannot convert $x") } With Regular Expressions
32
Bullet #4: Concurrency
33
val t0 = System.currentTimeMillis() def ten(i: Int) = { Thread.sleep(100) println(System.currentTimeMillis() - t0) i * 10 } (0 to 20).toList.map(ten).sum; (0 to 20).toList.par.map(ten).sum; List Parallelization
34
Actors
35
case class Greeting(who: String) class GreetingActor extends{ def receive = { case Greeting(who) ⇒ println(s"Hello $who") } } val system = ActorSystem("MySystem") val greeter = system.actorOf( Props[GreetingActor], name = "greeter") greeter ! Greeting("Charlie Parker")
36
Way way way more on actors
37
Bullet #4: the Ecosystem
38
Great IDE Integration
39
Typesafe stack Play/Slick/Akka/Spark/Activator
40
And still all Java
41
REPL (Read-Eval-Print-Loop)
43
So Many More Bullets
44
xml parsing: mixing xpath and the list manipulation for a mixed SAX/DOM approach; http queries; file system traversal and files parsing; Json serialization; dynamic classes, to add handle whatever method code; regular expression (ok, Perl is the king, but Scala is not bad); macros; string interpolation and reverse; more Java integration; abstract classes; profiling with yourkit or jProfiler context bound & parametric types streams foldLeft /: for loops structure map getOrElse case class implicit
45
Try it!
46
Further links coursera.org functional programming in scala course by Martin Odersky (and reactive, and parallel in Fall 2015); Scala for the Impatient by Carl S. Horstamnn is a good introduction to the language, specially for Java folks; Programming in Scala by Martin Odersky, Lex Spoon and Bill Venners is a pretty comprehensive one; daily scala blog, for inspiration; scala days conference (videos available); Scala meetups (monthly in Lausanne/Genève).
47
Try it!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.