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>>() {
Community
  • 1
  • 1
Mike Slinn
  • 7,705
  • 5
  • 51
  • 85

1 Answers1

2

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

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
  • The following always returns null in Java, although the equivalent Scala works fine. final AbstractFunction0 elseOption = new AbstractFunction0() { @Override public String apply() { return "default"; } }; final String notPresent = (new Some(System.getProperty("not.present"))).getOrElse(elseOption); Sorry, just cannot get code formatting to work in a comment. – Mike Slinn Jan 30 '12 at 13:18
  • @MikeSlinn Make another question about it. They don't charge per question here, y'know? :-) – Daniel C. Sobral Jan 30 '12 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`. – Daniel C. Sobral Jan 30 '12 at 16:25