40

Possible Duplicate:
Accessing scala.None from Java

In Java you can create an instance of Some using the constructor, i.e. new Some(value), but None has no partner class. How do you pass None to a Scala function from Java?

Community
  • 1
  • 1
Craig B.
  • 553
  • 1
  • 4
  • 10

5 Answers5

59

The scala.None$.MODULE$ thing doesn't always typecheck, for example this doesn't compile:

scala.Option<String> x = scala.None$.MODULE$;

because javac doesn't know about Scala's declaration-site variance, so you get:

J.java:3: incompatible types
found   : scala.None$
required: scala.Option<java.lang.String>
    scala.Option<String> x = scala.None$.MODULE$ ;

This does compile, though:

scala.Option<String> x = scala.Option.apply(null);

so that's a different way to get a None that is usable in more situations.

Seth Tisue
  • 29,985
  • 11
  • 82
  • 149
26

I think this ugly bit will work: scala.None$.MODULE$

There is no need for a new instance since one None is as good as another...

Mitch Blevins
  • 13,186
  • 3
  • 44
  • 32
11

You can access the singleton None instance from java using:

scala.None$.MODULE$
Randall Schulz
  • 26,420
  • 4
  • 61
  • 81
3

I've found this this generic function to be the most robust. You need to supply the type parameter, but the cast only appears once, which is nice. Some of the other solutions will not work in various scenarios, as your Java compiler may inform you.

import scala.None$;
import scala.Option;

public class ScalaLang {

    public static <T> Option<T> none() {
        return (Option<T>) None$.MODULE$;
    }
}

public class ExampleUsage {
    static {
        //for example, with java.lang.Long
        ScalaLang.<Long>none();
    }
}
Yuvi Masory
  • 2,644
  • 2
  • 27
  • 36
  • Thanks, this is one of the cleaner options around this. It clearly feels that calling Scala code from Java is less than optimal sometimes. :( – Per Lundberg Mar 05 '20 at 13:13
1

Faced with this stinkfest, my usual modus operandi is:

Scala:

object SomeScalaObject {
  def it = this
}

Java:

doStuff(SomeScalaObject.it());
Alex Cruise
  • 7,939
  • 1
  • 27
  • 40