I need to override the following Java method in a Scala class:
public class Test<T> {
public T test(T o, boolean x) {
if (x) {
return o;
}
return null;
}
}
With the following approach (in Scala), the compiler complains, “ of type Null doesn’t conform to expected type T”:
class Test2[T] extends Test[T] {
override def test(o: T, x: Boolean): T = {
if (x) {
return o
}
return null
}
}
I’ve also tried to define Option[T] as return value, but then again, the compiler complains that the method signatures wouldn’t match.
Any idea? - Thanks!
Edit:
Daniel’s suggestion works for the problem as originally posted; however, my actual problem unfortunately still differs slightly (by having the generic type parameter in the method, not class, definition) (sorry):
Java:
public class Test {
public <T> T test(T o, boolean x) {
if (x) {
return o;
}
return null;
}
}
Scala:
class Test2 extends Test {
override def test[T >: Null](o: T, x: Boolean): T = {
if (x) {
return o
}
return null
}
}
Compilation again fails with the error, “ of type Null doesn’t conform to expected type T”.
(I believe that’s because the override does not cover any possibilities - i.e., something of type Nothing could be passed to Test.test(…) - well, could it?
继续阅读与本文标签相同的文章
-
POLARDB MySQL 8.0 正式上线商用
2026-05-18栏目: 教程
-
MySQL 推出 90核 CPU 720GB 内存 独占物理机规格
2026-05-18栏目: 教程
-
基于 RocketMQ 的同城双活架构在美菜网的挑战与实践
2026-05-18栏目: 教程
-
账户系统如何应对高并发、热点账户等问题
2026-05-18栏目: 教程
-
阿里雷卷:Reactive 基金会的成立将对开发方式带来哪些影响?
2026-05-18栏目: 教程
