【问题标题】:What's the point of declaring an object as "final"?将对象声明为“最终”有什么意义?
【发布时间】:2014-09-27 21:57:57
【问题描述】:

我刚刚注意到可以在 Scala 中将对象声明为 final

final object O

这样做有什么意义?无论如何都不能从对象继承:

object A
object B extends A // not found: type A

【问题讨论】:

    标签: scala object inheritance final


    【解决方案1】:

    没有区别;对象定义始终是最终的。 language specification5.4 修饰符中明确提到了这一点:

    final 对于对象定义是多余的。

    【讨论】:

    • 最近有一个建议实际上禁止它:github.com/scala/bug/issues/11094
    • 它确实会对生成的字节码产生影响。根据 scala 版本,字节码可能包含也可能不包含 final 标志(2.11 添加它,2.12 没有)
    【解决方案2】:

    不是有人这样做,而是:

    $ scala -Yoverride-objects
    Welcome to Scala version 2.11.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_11).
    Type in expressions to have them evaluated.
    Type :help for more information.
    
    scala> trait A { object O } ; trait B extends A { override object O }
    defined trait A
    defined trait B
    
    scala> trait A { final object O } ; trait B extends A { override object O }
    <console>:8: error: overriding object O in trait A;
     object O cannot override final member
           trait A { final object O } ; trait B extends A { override object O }
                                                                            ^
    

    可能有时人们想要这样做。 (For instance.)

    【讨论】:

    • 这完全正确。不过,我花了一段时间才说服自己相信这一点。有关更详细、更痛苦的细节,请参阅 this duplicate question 中的更新。另见this question
    • -Yoverride-objects 一直无法正常工作,已完全从 Scala 2.13 中删除。
    • @SethTisue 基本上你是为了破坏我们的乐趣而获得报酬!如果这个网站有“自以为是的 Scala”与“任何事情都属于 Scala”的标签就好了。
    猜你喜欢
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    • 2016-12-09
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多