Because although they look similar, they mean different things (have different "semantics"). The Scala equivalent of your Java code:
public class SandboxJava { // Java
public Integer cards;
}
is this Scala code:
class SandboxScala {
var cards:Int = _
}
This has (practically) the same semantics as your Java example. In the code above cards
:
- is public-accessible
- is mutable (because of
var
)
- is initialized to its "default value" (because of
= _
)
Note that it is precisely because cards
is mutable (a var
) that you can initialize cards
to its "default value". That is: val cards = _
does not work, for obvious reasons (you can not change a val
afterwards, so you better initialize it with something meaningful).
As other answers have noted, your Scala version is wrong (for the reason I stated above: you have to initialize a val
with something).
If one corrected your Scala version with this:
class SandboxScala {
val cards:Int = SOME_INITIAL_VALUE
}
you could write something semantically equivalent in Java like this:
class SandboxJava {
public final int cards = SOME_INITIAL_VALUE
}
Note in this case that the Java compiler would also complain if you failed to provide an initial value for cards
.