Why are `privateval` and `private final val` different?

后端 未结 2 527
有刺的猬
有刺的猬 2020-11-28 20:50

I used to think that private val and private final val are same, until I saw section 4.1 in Scala Reference:

A constant valu

相关标签:
2条回答
  • 2020-11-28 21:08

    So, this is just a guess, but it was a perennial annoyance in Java that final static variables with a literal on the right-hand side get inlined into bytecode as constants. That engenders a performance benefit sure, but it causes binary compatibility of the definition to break if the "constant" ever changed. When defining a final static variable whose value might need to change, Java programmers have to resort to hacks like initializing the value with a method or constructor.

    A val in Scala is already final in the Java sense. It looks like Scala's designers are using the redundant modifier final to mean "permission to inline the constant value". So Scala programmers have complete control over this behavior without resorting to hacks: if they want an inlined constant, a value that should never change but is fast, they write "final val". if they want flexibility to change the value without breaking binary compatibility, just "val".

    0 讨论(0)
  • 2020-11-28 21:14

    I think the confusion here arises from conflating immutability with the semantics of final. vals can be overridden in child classes and therefore can't be treated as final unless marked as such explicitly.

    @Brian The REPL provides class scope at the line level. See:

    scala> $iw.getClass.getPackage
    res0: Package = package $line3
    
    scala> private val x = 5
    <console>:5: error: value x cannot be accessed in object $iw
      lazy val $result = `x`
    
    scala> private val x = 5; println(x);
    5
    
    0 讨论(0)
提交回复
热议问题