英文:
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 代码中使用 wait
和 notify
,可能会导致奇怪的行为。实际上,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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论