Instructor:
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, curly braces can be used
return
def f() : Int = e_1 e_2 ... e_nend f
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)end fact
(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<> (); // mutable variable, mutable listfinal List<Integer> ys = xs; // immutable variable, mutable listxs.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) // mutable variable, immutable listval ys = xs // immutable variable, immutable listxs (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;
List (1, 2, 1 + 2)1 :: 2 :: (1+2) :: Nil
Scala's :: is an infix operator to construct lists
::
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)
head
tail
val xs = List(1, 2, 3, 4)val x = xs.head // x == 1val ys = xs.tail // ys == List(2, 3, 4)