const in Java there is no function - reserved, but you canโt use anything. Declaring a Java variable as final is approximately equivalent .
Declaring a variable as val in Scala has similar guarantees for Java final -but Scala val - in fact, methods if they are not declared as private[this] . Here is an example:
class Test(val x: Int, private[this] val y: Int) { def z = y }
Here's what the compiled class 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, from this example, it can be seen that private[this] val is actually the Scala equivalent of Java final , since it just creates a field (without the getter method). However, this is a private field, so even this is not quite the same.
Another fun fact: Scala also has the final keyword! Scala final behaves similarly to how final works for classes in Java-ie, it prevents overriding. Here is 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); }
Note that the definition of final var makes the getter and setter methods final (i.e. you cannot override them), but not the supporting variable itself.
source share