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

后端 未结 2 540
有刺的猬
有刺的猬 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: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
    :5: error: value x cannot be accessed in object $iw
      lazy val $result = `x`
    
    scala> private val x = 5; println(x);
    5
    

提交回复
热议问题