How does val in scala differ from const in java?

Does anyone care how val in scala differs from const in java?
What are the technical differences? I suppose I understand what const is in C ++ and java. I have a feeling that "val" is somehow different and better in a way, but I just can't put my finger on it. Thanks

+6
source share
2 answers

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.

+9
source

A Scala val equivalent to a variable or final element in Java. A Scala var equivalent to a variable or non-t21> field in Java. (By the way, neither "var" nor "const" are Java terms.)

The aspect that is โ€œbetterโ€ in choosing Scala syntax for using val and var is that code using non-modifiable values โ€‹โ€‹is generally easier to understand. In Java, final is โ€œsyntax vinegar,โ€ and style guides tend to argue about whether to use final code to encourage better coding or skip final to avoid clutter. Scala does not have this puzzle because var and val are the same length, so you can more easily choose the one that makes the most sense.

0
source

Source: https://habr.com/ru/post/974134/


All Articles