Core_Dumped Core_Dumped - 5 months ago 12
Java Question

Why can't Scala have declared but undefined variables while Java can?

This compiles:

public class SandboxJava { //Java
public Integer cards;
}


But this does not:

class SandboxScala{
val cards:Int //Throws saying the class must be abstract to have undefined variables
}


Now I know the fact that
val
s must be initialized but why does not Scala have this functionality of having undefined variables in the first place?

Answer

In Java, a field that isn't explicitly initialized is still initialized. References are automatically initialized to null and scalar values to 0. The fact that it doesn't need to be explicit is just a kind of shorthand or syntactic sugar.

Local variables are a bit different. They're not automatically initialized, and they can be declared without initialization, but it's a compiler error to access them before initializing them.

public class Foo {
    public static void main(String[] args) {
        int x;
        if(x == 0) {
            System.out.println("Hello.");
        }
    }
}

Results in

Foo.java:4: error: variable x might not have been initialized
        if(x == 0) {
           ^