How to use scala.None from Java code [duplicate]

一世执手 提交于 2019-11-29 02:49:38

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...

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.

You can access the singleton None instance from java using:

scala.None$.MODULE$

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();
    }
}

Faced with this stinkfest, my usual modus operandi is:

Scala:

object SomeScalaObject {
  def it = this
}

Java:

doStuff(SomeScalaObject.it());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!