Instructor: Stefan Mitsch
Object-oriented programming
C
class C (f1:Int, val f2:Int, var f3:Int): //...
f1
f2
f3
val c = new C (2, 3, 5)
c
scala> val c = new C (2, 3, 5)c: C = C@8bd1b6ascala> c.f1<console>:10: error: value f1 is not a member of Cscala> c.f2res1: Int = 3scala> c.f3res2: Int = 5scala> c.f2 = 10<console>:9: error: reassignment to valscala> c.f3 = 10c.f3: Int = 10
public
Scala
class C1 (x:Int): def double() = x+xend C1
Expressed in Java
public class C1 { private final int x; public C1(int x) { this.x = x; } public int double() { return x+x; }}
class C2 (val x:Int): def double() = x+xend C2
public class C2 { private final int x; public C2(int x) { this.x = x; } public int x() { return x; } public int double() { return x+x; }}
class C3 (var x:Int): def double() = x+xend C3
public class C3 { private int x; public C3(int x) { this.x = x; } public int x() { return x; } public void setX(int x) { this.x = x; } public int double() { return x+x; }}
val
var
class C (f1:Int, val f2:Int, var f3:Int): val f4 = f1 * f2 var f5 = f2 * f3 println ("Constructing instance of C") def m (x:Int) : Int = // cannot reassign to f1, f2, f4 f3 = f3 + 1 f5 = f5 + 1 f1 * f3 * x end mend C
class D (f1: Int)
class E: private var n: Int = 0 def get () : Int = val tmp = n n = n + 1 tmpend E
val o: E = new E()o.get()
def
def x = 5
val x = 5
lazy val
class C: val x = 1 lazy val y = 1 + 2 def z = 1end C
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 = 1end C
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; }}
object
object C: var count:Int = 0end CC.count = C.count + 1
main
Java
public class C { public static void main (String[] args) { //... }}
object C: def main (args:Array[String]) : Unit = //... end mainend C
static
class C { public int f1; public int m1 () { return f1; } public static int f2; public static int m2 () { return f2; }}
Scala: Companion object replaces static
class C: var f1:Int = 0 def m1 () : Int = f1object C: var f2:Int = 0 def m2 () : Int = f2