Assign immutable int value | val x = 3 |
Assign mutable int value | var x = 3 |
Assign immutable value with explicit type | val x: Int = 27 |
Assign lazily evaluated value | lazy val y = print("Sleeping in.") |
Bind a function to a name | val f = (x: Int) => x * x |
Bind a function to a name with explicit type | val f: Int => Int = (x: Int) => x * x |
Define a method | def f(x: Int) = x * x |
Define a method with explicit typing | def f(x: Int): Int = x * x |
Define a class | class Hopper(someParam: Int) { ... } |
Define an object | object Hopper(someParam: Int) { ... } |
Define a trait | trait Grace { ... } |
Get first element of sequence | Seq(1,2,3).head |
If switch | val result = if(x > 0) "Positive!" |
Get all elements of sequence except first | Seq(1,2,3).tail |
Loop through a list | for { x <- Seq(1,2,3) } print(x) |
Nested Looping | for { x <- Seq(1,2,3) y <- Seq(4,5,6) } print(x + ":" + y) |
For each list element execute function | List(1,2,3).foreach { println } |
Print to standard out | print("Ada Lovelace") |
Sort a list alphanumerically | List('b','c','a').sorted |