Val vs. Var
- vals are immutable; cannot be re-assgin
- compiler can infer types
- vars can be re-assign
Expressions
val x = 1 + 2 // EXPRESSION
- instruction vs. expression
- scala forces everything to be an Zexpression
val condition = true
val conditionValue =. if condition 5 else 3 // IF EXPRESSION
Called-by-Value VS. Called-by-Name
object CBNvsCBV extends App {def calledByValue(x: Long): Unit = {
println("by value: " + x) // timestamp
println("by value: " + x) // timestamp
}
def calledByName(x: => Long): Unit = {
println("by name: " + x) // timestamp1
println("by name: " + x) // timestamp2
}
calledByValue(1257387745764245L)
calledByName(System.nanoTime())
def infinite(): Int = 1 + infinite()
def printFirst(x: Int, y: => Int) = println(x)
// printFirst(infinite(), 34) // stack overflow
printFirst(34, infinite())
}
Difference:
By Value: evaluate System.nanoTime() first, and use the value throughout the execution
By Name: evaluate System.nanoTime() each time
- lazy evaluation: if the parameter called by name is never used, it will never be evaluated
Useful When:
- Lazy stream
- Exception handling with the Try type