How to initialize empty variables from your own type in Scala?

My problem is understanding Scala syntax. I come from a Java background. I am trying to make a variable of the same type as the class in which it is located. Example:

class Exp { var exp1: Exp; } 

I get this error:

 Driver.scala:4: error: class Exp needs to be abstract, since variable exp1 is not defined (Note that variables need to be initialized to be defined) class Exp { 

Can someone explain why I cannot do this? I am new to the language. Any explanation will help to better understand it.

+8
syntax scala
source share
1 answer

Because you need to initialize it. Otherwise, the compiler believes that you only need the interface of the variable: the getter and setter methods. This is very similar to how a method without a body is abstract. The following initializes it to zero and gives you a valid concrete class with a specific variable.

 class Exp { var exp1: Exp = _; } 

This use of _ means "default", where the default is null for reference types and 0, false, or something similar for types without a reference.

+16
source share

All Articles