5

Same idea as my previous question, just a little more advanced. I want to write the following Scala code in Java:

Option(System.getProperty("not.present")).orElse(Some("default")).get

I tried this:

    final Function0<Option<String>> elseOption = new Function0<Option<String>>() { 
        @Override public Option<String> apply() { 
            return new Some<String>("default"); 
        }
    };

    final Option<String> notPresent =
        new Some<String>(System.getProperty("not.present")).
        orElse(elseOption).get();

But I get:

<anonymous OptionDemo$1> is not abstract and does not override abstract method apply$mcD$sp() in scala.Function0
[error]       orElse(new Function0<Option<String>>() {
3
  • 4
    By the way: Option(System.getProperty("x")) getOrElse "default" is more concise and clear than what you have Commented Jan 30, 2012 at 7:59
  • +1 on oxbow_lakes, try to always avoid doing ".get" Commented Jan 30, 2012 at 10:24
  • Good catch! I now have: Option(System.getProperty("not.present")).getOrElse("default")
    – Mike Slinn
    Commented Jan 30, 2012 at 13:16

1 Answer 1

2

Extend AbstractFunction0 instead of Function0. That should give you the trait-provided methods.

3
  • The following always returns null in Java, although the equivalent Scala works fine. final AbstractFunction0<String> elseOption = new AbstractFunction0<String>() { @Override public String apply() { return "default"; } }; final String notPresent = (new Some<String>(System.getProperty("not.present"))).getOrElse(elseOption); Sorry, just cannot get code formatting to work in a comment.
    – Mike Slinn
    Commented Jan 30, 2012 at 13:18
  • @MikeSlinn Make another question about it. They don't charge per question here, y'know? :-) Commented Jan 30, 2012 at 16:24
  • @MikeSlinn but, basically, because you used Some, it will always return the content of Some. It is Option, not Some, that turns nulls into None. Commented Jan 30, 2012 at 16:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.