问题
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
回答1:
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.
回答2:
A Scala val
is equivalent to a final
variable or field in Java. A Scala var
is equivalent to a non-final
variable or field in Java. (By the way, neither "var" nor "const" are Java terms.)
The aspect that's "better" about Scala's syntax choice to use val
and var
is that code using non-modifiable values is generally easier to understand. In Java, final
is "syntactic vinegar", and style guides tend to argue over whether code should use final
to encourage better coding or omit final
to avoid the clutter. Scala doesn't have this conundrum because the var
and val
are exactly the same length, so you're a bit more free to just choose the one that makes the most sense.
来源:https://stackoverflow.com/questions/25417450/how-is-val-in-scala-different-from-const-in-java