声明一个带有名为“Wait”的变量的特性会导致编译器错误。

huangapple go评论69阅读模式
英文:

Declaring A Trait With A Variable Named Wait Gives Override Compiler Error

问题

以下是翻译好的内容:

给定以下特质:

trait Foo {

  final val wait = "wait"

}

在编译时,它会产生以下覆盖编译错误:

值 'wait' 无法覆盖 final 成员

在特质内部声明变量如上所示,似乎与 Object 类中的以下Java方法发生冲突:

    public final void wait() throws InterruptedException {
        this.wait(0L);
    }

这是一个错误还是预期行为?

英文:

Given the following trait:

trait Foo {

  final val wait = "wait"

}

on compilation it emits the following override compiler error:

Value 'wait' cannot override final member

Declaring a variable inside a trait as above seems to clash with the following Java method in the Object class:

    public final void wait() throws InterruptedException {
        this.wait(0L);
    }

Is this a bug or desired behaviour?

答案1

得分: 2

wait 是在 JVM 上由 Object 定义的一个 final 方法。任何其他对象都会扩展自 java.lang.Object,因此你无法覆盖/定义其中的 final 方法。

这是预期的,否则如果你试图在使用了来自 Scala 代码部分的对象的 Java 代码中使用 waitnotify,可能会导致奇怪的行为。实际上,Scala 试图遵循 Java 定义的所有契约,以确保安全。

英文:

wait is a final method defined in Object on JVM. Any other object extends java.lang.Object, so you cannot override/define methods that are final in it.

This is expected, otherwise you would end up with a weird behavior if you tried to use wait and notify in Java code where object came from part of the code written in Scala. Actually, Scala tries to hold all contracts that Java defined to be on a safe side of things.

答案2

得分: 2

这个答案中,你可以看到val字段实际上还会创建一个与该字段名称相同的getter方法 - 在你的情况下是wait()。由于这与Object上的最终wait()方法冲突,所以这是可以预料的。

英文:

In this answer you see that a val field actually also creates a getter method with the name of the field - in your case wait(). Since that clashes with the final wait() method on Object, that is indeed expected.

huangapple
  • 本文由 发表于 2020年5月19日 17:47:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/61888023.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定