Unless I've been doing it wrong. It doesn't seem like we can do things like:
var x;
x = 1;
in Scala, but rather you have to declare and assign a value to it. Are there any reasons for why this is the case?
In Scala the general rule is that you should always use a val field unless there's a good reason not to. This simple rule (a) makes your code more like algebra and (b) helps get you started down the path to functional programming, where all fields are immutable.
The keywords var and val both are used to assign memory to variables at the running only. The difference is in the mutability of variables that are initialized using these keywords. var keyword initializes variables that are mutable, and the val keyword initializes variables that are immutable.
The multiple assignments can be possible in Scala in one line by using 'val' keyword with variable name separated by commas and the "=" sign with the value for the variable. In the above example, you can see all of the variables a,b, and c get assigned to value 1 as follows.
In Scala, reassignment to val is not allowed, but we can create a new val and assign the value to it. We can see an error when reassigning the values to a val . As a workaround, we can assign the result to a new val and use it.
The obvious reason is to help not leave variables uninitialized. Note that in your declaration without initialization, you will also need to specify the type.
var x: Type;
gives the following error:
only classes can have declared but undefined members (Note that variables need to be initialized to be defined)
Actually only abstract classes can declare members without defining them. You can still get the desired behavior (variables initialized to a default value) as
var x: Type = _
If Type
is a reference type, x
will be null
. This scenario is useful, for example, in case where a factory method completes initialization of an object after object construction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With