Scala is an object-oriented and functional programming language that runs on the Java Virtual Machine. It was designed by Martin Odersky and developed at EPFL in Switzerland. Scala combines object-oriented and functional programming principles, including support for immutable data structures, pattern matching, and closures. It interoperates seamlessly with existing Java code and libraries.
7. No statements,
just expressions
• Everything returns something
• for, while and if/else are expressions
• Unit is the equivalent to Java’s void
• Explicit return is optional:
def plus2(x:Int) = x+2
8. def foo(arg:String)={
if (arg==null) {
throw new RuntimeException(“Ups”)
} else {
“foobar”
}
}
def foo(arg:String): String ={
if (arg!=null) {
throw new RuntimeException(“Ups”)
} else {
return “foobar”
}
}
9. Vals and Vars
def foo() {
val x = “immutable”
// Java: final x
var y = “mutable”
}
10. “Operator Overloading”
class Foo(value:Int) {
def +(other:Foo) = value + other.value
}
val foo = new Foo(13)
val foo2 = new Foo(23)
println(foo + foo2) // outputs “36”
println(foo.+(foo2)) // outputs “36”
11. class Foo(val value:Int) {
def unary_! = quot;!!!quot; + value + quot;!!!quot;
def *:(multiple:Int) = value * multiple
}
var foo = new Foo(62)
!foo // result: String = “!!!62!!!”
foo.!() // the same
2 *: foo // result: Int = 124
foo.*:(2)// the same
13. Constructors
class Foo(val immutable:String,
var mutable:String)
var f = new Foo(“foo”,”bar”)
f.immutable == f.mutable //false
f.mutable = “foo”
f.immutable == f.mutable //true
16. Traits
trait Ordered[A] {
def compare(that: A): Int
def < (that: A) = (this compare that)< 0
def > (that: A) = (this compare that)> 0
def <= (that: A) = (this compare that)<=0
def >= (that: A) = (this compare that)>=0
}
17. class Animal
trait Furry extends Animal
trait FourLegged extends Animal with HasLegs
trait HasLegs extends Animal
class Cat extends Animal with Furry with FourLegged
18. Mixing in during
construction
trait Foo {
def foo(text:String) =
println(text+toString)
}
class Now {
override def toString =
new java.util.Date().toString()
}
val now = new Now with Foo
now foo “It’s ” // “It’s <current time>“
20. Rich Wrappers
scala> 42 max 43
res7: Int = 43
scala> 42 min 43
res8: Int = 42
scala> 1 until 5
res9: Range = Range(1, 2, 3, 4)
scala> 1 to 5
res10: Range.Inclusive = Range(1, 2, 3, 4, 5)
scala> 3.abs
res11: Int = 3
scala> (-3).abs
res12: Int = 3
21. Functional Programming
Functions as Values
No side effects (purity)
Has it’s roots in Alonzo Church’s
“Lambda Calculus”
Lisp, Scheme, SML, Erlang, Haskell,
OCaml, F#
22. Functions as Objects
val multiply = (x:Int, y:Int) => x * y
val altMulti:(Int,Int)=>Int = _ * _
multiply(2,3) == altMulti(2,3)
23. Higher-order Functions
def timeBlock(block: =>Unit) {
val start = System.currentTimeMillis()
block
printf(quot;Block took {0} millisecondsnquot;,
System.currentTimeMillis - start)
}
timeBlock {
(1 to 4).foreach{x => println(quot;x = quot;+x)}
}
24. Currying and Loan Pattern
def using[A](r : File)
(f : InputStream => A) : A {
val in = getStream(r)
try {
f(in)
} finally {
in.close()
}
}
using(myRes) { in =>
in.read()
}
25. Closures make ...
... querying Structures easier
and creation of
new control structures possible
27. Tuples
val pair = (99, quot;Luftballonsquot;)
println(pair._1)
println(pair._2)
// type is Tuple2[Int, String]
28. Case Classes
abstract class Expr
case class Var(name: String) extends Expr
case class Number(num: Double) extends Expr
case class UnOp(operator: String, arg: Expr)
extends Expr
case class BinOp(left: Expr,
operator: String, right: Expr) extends Expr
29. Case Classes (2)
val expr =
BinOp(Number(2), “*”, UnOp(“-”,Var(“x”))
def simplify(expr: Expr) = expr match {
case UnOp(quot;-quot;, UnOp(quot;-quot;, e)) => e
case BinOp(e, quot;+quot;, Number(0)) => e
case BinOp(e, quot;*quot;, Number(1)) => e
case _ => expr
}
30. Pattern Matching (1)
def describe(x: Any) = x match {
case 5 => quot;fivequot;
case true => quot;truthquot;
case quot;helloquot; => quot;hi!quot;
case Nil => quot;the empty listquot;
case _ => quot;something elsequot;
}
31. Pattern Matching (2)
def describe(x: Any) = x match {
case x::xs => “head:”+x+” tail:”+xs
case List(1,_*,2) => quot;a special listquot;
case (_,quot;helloquot;) => quot;hi tuple!quot;
case _ => quot;something elsequot;
}
32. Extractors
object EMail {
def unapply(str:String):Option((String,String))={
val parts = str split quot;@quot;
if (parts.length == 2)
Some(parts(0), parts(1))
else
None
}
}
def isAllowed(email:String) = {
email match {
case Email(alias,”web.de”) => false
case _ => true
}
}
33. For-Expressions
case class Person(name: String,
isMale: Boolean,
children: Person*)
val lara = Person(quot;Laraquot;, false)
val bob = Person(quot;Bobquot;, true)
val julie = Person(quot;Juliequot;, false, lara, bob)
val persons = List(lara, bob, julie)
for (p <- persons)
println(p.name)
34. Finding pairs of
mother and kid in Java
List<Pair> result = new ArrayList<Pair>();
for(Person p : persons) {
if (!p.isMale()) {
for(Person c: p.children) {
result.add(
new Pair(p.getName(),c.getName()));
}
}
}
35. In Scala using
higher-order functions
persons filter (p => !p.isMale)
flatMap (p =>
(p.children map (c =>
(p.name, c.name))))
37. More to look at...
• Type Parameterization
• XML literals
• Combining Java and Scala
(In short: Calling Java from Scala is straight
forward, but the other way round needs a
little bit of thinking)
• Actor library
• Combinator parser library