Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Why is it necessary to assign values to a var/val during declaration

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?

like image 525
Stupid.Fat.Cat Avatar asked Jul 08 '13 16:07

Stupid.Fat.Cat


People also ask

Why do we use val in Scala?

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.

What is var and val in Scala?

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.

How do I assign a value to a variable in Scala?

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.

How do I assign a val in Scala?

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.


1 Answers

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.

like image 132
r.v Avatar answered Oct 18 '22 01:10

r.v