-
-
Save coacoas/3013872 to your computer and use it in GitHub Desktop.
Using Scala's Option from Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package net.ccombs.scalaFromJava; | |
import scala.Option; | |
import scala.Some; | |
import scala.runtime.AbstractFunction0; | |
/** | |
* OptionExample | |
*/ | |
public class OptionExample { | |
/** | |
* Construct a Scala Option[T] from a given value. | |
*/ | |
private static final <T> scala.Option<T> option(final T value) { | |
return (value != null)?new Some<T>(value):scala.Option.apply((T) null); | |
} | |
public static void main(final String args[]) { | |
final Some<String> s1 = (Some<String>) option("s1"); | |
// this doesn't work | |
// final None n = (None) option(null); | |
final Option<String> n = option(null); | |
// Compiles, even though n is Option<String>. It works | |
// at runtime, since getOrElse returns an Integer | |
Integer test = n.getOrElse(new AbstractFunction0<Integer>() { | |
@Override | |
public Integer apply() { | |
return 4; | |
} }); | |
// Compiles, but gives ClassCastException at runtime | |
Integer test2 = s1.getOrElse(new AbstractFunction0<Integer>() { | |
@Override | |
public Integer apply() { | |
return 4; | |
} }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment