How can you access scala.None
from Java?
The last line causes the compiler to die with "type scala.None does not take parameters".
import scala.Option;
import scala.Some;
import scala.None;
final Option<String> object1 = new Some<String>("Hi there");
final Option<String> object2 = new None<String>();
This fails with "cannot find symbol constructor None()":
final Option<String> object2 = new None();
This fails with "cannot find symbol variable None":
final Option<String> object2 = None;
In 2007 this used to work, but then Scala changed. The Java compiler gives error: incompatible types
:
final Option<String> object2 = scala.None$.MODULE$;
Using Scala 2.10.2 (not sure at what version when this came in):
You can import
And then:
Using Scala version 2.11.4 the only thing that worked out in my case, was
Update: a day later...
without the type parameter does work too, as it should. For some reason I couldn't get Intellij to compile the code on my first attempt. I had to pass the secondary type parameter. Now it compiles, just don't ask
Not to put too fine a point on it, but one shouldn't rely on static forwarders, as they might not get generated under certain circumstances. For instance,
Some
doesn't have static forwarders for its object companion.The current way of accessing methods on an object companion is this:
Option$
is the class for the object companion ofOption
.MODULE$
is a final public static field that contains the sole instance ofOption$
(in other words, the object companion).This might work:
You can do the following (I tested it out and it works fine for me with Scala 2.9.1 and Java 1.6):