Anyone care to elaborate on how val in scala is different from const in java?
What are the technical differences? I believe I understand what "const" is in c++ and java. I get the feeling that "val" is somehow different and better in some sense but I just can't put my finger on it. Thanks
Both "val" and "const val" are used for declaring read-only properties of a class. The variables declared as const are initialized at the runtime. val deals with the immutable property of a class, that is, only read-only variables can be declared using val.
Scala variables come in two shapes. Values and variables. A value variable is really just a constant, meaning once assigned, you cannot change its value. It is immutable in other words.
By contrast, Scala has two types of variables: val creates an immutable variable (like final in Java) var creates a mutable variable.
VAL(Value)The object stored using val cannot be changed, it cannot be reassigned, it is just like the final keyword in java. val is immutable. Once assigned the val becomes read-only, however, the properties of a val object could be changed, but the object itself is read-only.
const
in Java has no function—it's reserved but you can't actually use it for anything. Declaring a Java variable as final
is roughly equivalent.
Declaring a variable as a val
in Scala has similar guarantees to Java final
—but Scala val
s are actually methods unless they're declared as private[this]
. Here's an example:
class Test(val x: Int, private[this] val y: Int) {
def z = y
}
Here's what the compiled classfile looks like:
$ javap -p Test
Compiled from "Test.scala"
public class Test {
private final int x;
private final int y;
public int x();
public int z();
public Test(int, int);
}
So it's clear from this example that private[this] val
is actually Scala's equivalent of Java's final
in that it just creates a field (no getter method). However, it's a private field, so even that's not quite the same.
Another fun fact: Scala also has a final
keyword! Scala's final
behaves similarly to how final
works for classes in Java—i.e. it prevents overriding. Here's another example:
final class Test(final val x: Int, final var y: Int) { }
And the resulting class:
$ javap -p Test
Compiled from "Test.scala"
public final class Test {
private final int x;
private int y;
public final int x();
public final int y();
public final void y_$eq(int);
public Test(int, int);
}
Notice that the final var
definition makes the getter and setter methods final (i.e. you can't override them), but not the backing variable itself.
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