给定这些 Java 类定义:
class Base {
int value;
public <T extends Base> T self() {
return (T) this;
}
}
class Derived extends Base {}
这段 Java 代码编译得很好:
new Derived().self();
但是这段 Scala 代码无法运行:
(new Derived).self(); // runtime error
Rumtime 错误:
java.lang.ClassCastException: Derived cannot be cast to scala.runtime.Nothing$
为什么它不起作用,如何解决?
最佳答案
在 Scala 中这个方法看起来像 self[T <: Base](): T
.在 (new Derived).self()
你没有指定 T
.这意味着最具体的类型 - Nothing
.
所以 (new Derived).self()
实际上是 (new Derived).self[Nothing]()
.
你可以试试 (new Derived).self[Derived]()
或 val d: Derived = (new Derived).self()
.
关于java - 为什么 Java 中的 `(T)this` 不能在 Scala 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16410604/