Instructor: Stefan Mitsch
How to combine multiple programming paradigms in a single language?
false || true
1 + 2
("hello" + " " + "world").length
val dir = java.io.File ("/tmp")dir.listFiles.filter (f => f.isDirectory && f.getName.startsWith ("c"))
5:Int
Int
5.toDouble
scala.Int
5.+ (6)
scala.runtime.RichInt
5.max (6)
e1.f(e2)
e1 f e2
5 + 6
5 max 6
def f () = 5 - "hello" // rejected by type checker
java.lang.Object
scala.AnyRef
int x = 10; // declare and initialize xx = 11; // assignment to x OK
var x = 10 // declare and initialize xx = 11 // assignment to x OK
final int x = 10; // declare and initialize xx = 11; // assignment to x fails// error: cannot assign a value to final variable x
const int x = 10; // declare and initialize xx = 11; // assignment to x fails// error: assignment of read-only variable ‘x’
val x = 10 // declare and initialize xx = 11 // assignment to x fails// error: reassignment to val
int f() { s_1; s_2; ... return ...;}
def f() = {e_1; e_2; ...; return e_n}
Semicolons and return optional
return
def f() : Int = { e_1 e_2 ... e_n}
def plus (x:Int, y:Int) : Int = x + ydef times (x: Int, y:Int) = x * y
def fact (n:Int) : Int = if n <= 1 then 1 else n * fact (n - 1)
def fact(n:Int) : Int = println("called with n=%d".format(n)) if n <= 1 then println("no recursive call") 1 else println("making recursive call") n * fact(n - 1)
def
def x = 5
val
val x = 5
lazy val
Scala
class C: val x = 1 lazy val y = 1 + 2 def z = 1
Expressed in Java
public class C { private final int x = 1; private Integer y = null; public int x() { return x; } public int y() { if (y == null) y = 1 + 2; return y; } public int z() { return 1; } }
class C: val x = 1 var z = 1
public class C { private final int x = 1; private int z = 1; public int x() { return x; } public int z() { return z; } public void z_$eq(int z) { this.z = z; }}
(1, "hello")
List(1, 2, 3)
1 :: 2 :: 3 :: Nil
scala.collection
scala.collection.immutable
scala.collection.mutable
java.util
Array[Int]
List<Integer> xs = new List<> ();final List<Integer> ys = xs; // aliasingxs.add (4); ys.add (5); // list is mutable through both referencesxs = new List<> (); // reference is mutableys = new List<> (); // fails; reference is immutable
var xs = List (4, 5, 6)val ys = xsxs (1) = 7; ys (1) = 3 // fails; list is immutablexs = List (0) // reference is mutableys = List () // fails; reference is immutable
Tuples are immutable heterogeneous complex data items
val p : (Int, String) = (5, "hello")val x : Int = p(0)
public class Pair<X,Y> { final X x; final Y y; public Pair (X x, Y y) { this.x = x; this.y = y; }}Pair<Integer, String> p = new Pair<> (5, "hello");int x = p.x;
::
val xs = 11 :: (21 :: (31 :: (41 :: Nil))) // List(11, 21, 31, 41)val xs = 11 :: 21 :: 31 :: 41 :: Nil // right associative// method-call style, not encouraged!val xs = Nil.::(41).::(31).::(21).::(11)
List (1, 2, 1 + 2)1 :: 2 :: (1+2) :: Nil
head
tail
xs.headxs.tail