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?

收藏 打印