Skip to content

Instantly share code, notes, and snippets.

@coacoas
Forked from ClintCombs/OptionExample.java
Created June 28, 2012 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coacoas/3013872 to your computer and use it in GitHub Desktop.
Save coacoas/3013872 to your computer and use it in GitHub Desktop.
Using Scala's Option from Java
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