Accessing scala.None from Java

前端 未结 6 1962
南笙
南笙 2020-12-04 01:14

How can you access scala.None from Java?

The last line causes the compiler to die with \"type scala.None does not take parameters\".

imp         


        
相关标签:
6条回答
  • 2020-12-04 01:47

    You can import

    import scala.compat.java8.OptionConverters;
    

    And then:

    OptionConverters.<YourType>toScala(Optional.empty())
    
    0 讨论(0)
  • 2020-12-04 01:52

    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:

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

    Option$ is the class for the object companion of Option. MODULE$ is a final public static field that contains the sole instance of Option$ (in other words, the object companion).

    0 讨论(0)
  • 2020-12-04 01:56

    Using Scala version 2.11.4 the only thing that worked out in my case, was

    Option<String> maybeAmount = (amount != MISSING_STOCKAMOUNT) 
    ? Some.apply(amount+"") : Option.<String>apply(null); // can you feel the pain??
    

    Update: a day later...

    Option.apply(null);
    

    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

    0 讨论(0)
  • 2020-12-04 01:58

    You can do the following (I tested it out and it works fine for me with Scala 2.9.1 and Java 1.6):

     final Option<String> obj1 = Some.apply(null) // This will give you a None;
     System.out.println(obj1.getClass()); // will print "class scala.None$
    
     final Option<String> obj2 = Some.apply("Something");
     System.out.println(obj2.getClass()); //will print "class scala.Some
    
    0 讨论(0)
  • 2020-12-04 02:04

    Using Scala 2.10.2 (not sure at what version when this came in):

    final Option<String> none = Option.empty();
    
    0 讨论(0)
  • 2020-12-04 02:05

    This might work:

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

    def apply [A] (x: A): Option[A]
    An Option factory which creates Some(x) if the argument is not null, and None if it is null.

    0 讨论(0)
提交回复
热议问题