This is the second installment of this series. The first post in the series gives you a bit more context. Anyway, this is my try to answer Scala Interview grade Questions I found in a blog post by Signify. You can find alternate answers here.
Language Questions
What is the difference between a var
, a val
and def
?
All these keywords are for declaring something. var
declares a variable, val
declares a variable that cannot be re-assigned and def
declares a function.
scala
var a = 3
val b = 3
def c = 3
In the above code, a
is a variable as you can find in almost every language, you can increment it, re-assign it. Standard stuff.
b
is a variable bound to value 3 forever? Attempting to change its value results in a compile-time error. c
is a parameterless function that returns 3. Interestingly a
, b
and c
evaluate to the integer 3. Also note that val
just prevents reassignment, not value change. E.g. in the following code:
scala
class Foo {
private var a: Int = 3
def change( newA : Int ) : Unit = { a = newA }
}
val x = new Foo()
x.change(8)
There is no compile-time error because you are not changing the bound between x
and the instance that references. You are just changing the instance.