Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

syntax

scala

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.

like image 262
Andy Avatar asked Mar 29 '12 22:03

Andy


People also ask

How do I assign a null value in Scala?

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.

Which Scala keyword is used to initialize variables?

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.

What is difference between Val and VAR in Scala?

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.


1 Answers

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.

like image 182
James Iry Avatar answered Oct 18 '22 18:10

James Iry