I used to think that private val
and private final val
are same, until I saw section 4.1 in Scala Reference:
A constant value definition is of the form
final val x = e
where e is a constant expression (§6.24). The final modifier must be present and no type annotation may be given. References to the constant value x are themselves treated as constant expressions; in the generated code they are replaced by the definition’s right-hand side e.
And I have written a test:
class PrivateVal {
private val privateVal = 0
def testPrivateVal = privateVal
private final val privateFinalVal = 1
def testPrivateFinalVal = privateFinalVal
}
javap -c
output:
Compiled from "PrivateVal.scala"
public class PrivateVal {
public int testPrivateVal();
Code:
0: aload_0
1: invokespecial #19 // Method privateVal:()I
4: ireturn
public int testPrivateFinalVal();
Code:
0: iconst_1
1: ireturn
public PrivateVal();
Code:
0: aload_0
1: invokespecial #24 // Method java/lang/Object."<init>":()V
4: aload_0
5: iconst_0
6: putfield #14 // Field privateVal:I
9: return
}
The byte code is just as Scala Reference said: private val
is not private final val
.
Why doesn't scalac just treat private val
as private final val
? Is there any underlying reason?
val
is already immutable, why do we need thefinal
keyword at all in Scala? Why can't the compiler treat allval
s the same way asfinal val
s? – Jesperprivate
scope modifier has the same semantics aspackage private
in Java. You may mean to sayprivate[this]
. – Connor Doyleprivate
mean that it is only visible to instances of this class,private[this]
only this instance - except for instances of the same class,private
does not allow anyone (include from the same package) to access the value. – Make42