My problem is understanding is the syntax of Scala. I come from a Java background. I am trying to make a variable of the same type as the class it is in. Example:
class Exp {
var exp1: Exp;
}
I am getting 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 would help in understanding it better.
You can't. Double is a value type, and you can only assign null to reference types. Instead, the Scala compiler replaces null with a default value of 0.0.
Immutable variables are defined by using the val keyword. The first letter of data type should be in capital letter because in Scala data type is treated as objects. Here value is the name of the variable. Variable name should be in lower case.
The difference between val and var is that val makes a variable immutable — like final in Java — and var makes a variable mutable. Because val fields can't vary, some people refer to them as values rather than variables.
Because you need to initialize it. Otherwise the compiler thinks you want only the variable's interface: the getter and setter methods. It's very similar to how a method without a body is abstract. The following will initialize it to null and give you a valid concrete class with a concrete variable.
class Exp {
var exp1: Exp = _;
}
This use of _ means "default value" where the default is null for reference types and 0, false, or something similar for non-reference types.
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