user3346601
user3346601

Reputation: 1049

Using Option[Boolean] from Java

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

Answers (4)

Boaz
Boaz

Reputation: 1460

From the class description:

Boolean (equivalent to Java's boolean primitive type) is a subtype of [[scala.AnyVal]]. Instances of Boolean 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

Ruchita Surve
Ruchita Surve

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

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369420

I can't test this right now, but my best guess is that you have some imports mixed up, and thus try to override Option<scala.Boolean> with Option<java.lang.Boolean>.

Upvotes: 2

Zolt&#225;n
Zolt&#225;n

Reputation: 22146

Could you try

public class MyClass implements WithBoolean {
  @Override
  public Option<? super Boolean> doSth() {
    return null;
  }
}

Upvotes: 1

Related Questions