Reputation: 1049
I've got a Scala Trait with a method that returns Option[Boolean]. I'd like to write a Java class that implements this trait. Unfortunately the compiler complains about the following code:
trait WithBoolean {
def doSth(): Option[Boolean]
}
public class MyClass implements WithBoolean {
@Override
public Option<Boolean> doSth() {
return null;
}
}
The compile error is:
doSth() in MyClass cannot implement doSth() in WithBoolean
public Option<Boolean> doSth() {
^
return type Option<Boolean> is not compatible with Option<Object>
It does compile if i change the code slightly:
public class MyClass implements WithBoolean {
@Override
public Option<Object> doSth() { //return type has been changed to Object
return null;
}
}
But this is obviously not a nice solution. What do I need to change in order to be able to use the correct return type?
Upvotes: 4
Views: 1629
Reputation: 1460
From the class description:
Boolean
(equivalent to Java'sboolean
primitive type) is a subtype of [[scala.AnyVal]]. Instances ofBoolean
are not represented by an object in the underlying runtime system.
Java Boolean extends AnyRef
(more about this here).
AnyRef
and AnyVal
both extends Any
which is equivalent to java.lang.Object
.
This is why only Option<Object>
works.
If you want type safety you could do this:
trait WithBoolean {
def doSth(): Option[Boolean]
}
abstract class WithBooleanForJava extends WithBoolean {
override def doSth(): Option[Boolean] = doSthJava().map(Boolean.box(_))
def doSthJava(): Option[java.lang.Boolean]
}
So you java class will look like you wanted:
public class MyClass extends WithBooleanForJava {
@Override
public Option<Boolean> doSthJava() {
return null;
}
}
Upvotes: 0
Reputation: 1
You can try this :
(value != null)?new Some<T>(value):scala.Option.apply((T) null);
(value != null)?new Some<Boolean>(value):scala.Option.apply((Boolean) null);
Upvotes: 0
Reputation: 369420
I can't test this right now, but my best guess is that you have some import
s mixed up, and thus try to override Option<scala.Boolean>
with Option<java.lang.Boolean>
.
Upvotes: 2
Reputation: 22146
Could you try
public class MyClass implements WithBoolean {
@Override
public Option<? super Boolean> doSth() {
return null;
}
}
Upvotes: 1