Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
java version of scala Option
package fupfin;
import java.util.NoSuchElementException;
/**
* A base class of simple value container that represents optional values. You can
* use subclass Some<A> for some existent values or None for non existent values.
* This is java version of scala Option class.
*
* @author fupfin@gmail.com
* @see scala.Option
* @param <T> type of the contained value
*/
public abstract class Option<T> {
public abstract T get();
public abstract T getOrElse(T defaultValue);
public abstract boolean isDefined();
public abstract boolean isEmpty();
public static final Option<Object> NONE = new None();
@SuppressWarnings("unchecked")
public static <A> Option<A> none() {
return (Option<A>) NONE;
}
public static <A> Option<A> some(A value) {
return new Some<A>(value);
}
public static class Some<T> extends Option<T> {
private T value;
public Some(T value) {
super();
this.value = value;
}
@Override
public final T get() {
return value;
}
@Override
public final T getOrElse(T defaultValue) {
return get();
}
@Override
public final boolean isDefined() { return true; }
@Override
public final boolean isEmpty() { return !isDefined(); }
}
public static class None extends Option<Object> {
private None() {
super();
}
@Override public Object get() {
throw new NoSuchElementException();
}
@Override public Object getOrElse(Object defaultValue) {
return defaultValue;
}
@Override public boolean isDefined() { return false; }
@Override public boolean isEmpty() { return true; }
};
}
package fupfin;
import static fupfin.Option.*;
import static org.junit.Assert.*;
import java.util.NoSuchElementException;
import org.junit.Test;
public class OptionTest {
private static final String TEST_STRING = "a";
@Test
public void testNone() {
Option<String> result = none();
assertFalse(result.isDefined());
assertTrue(result.isEmpty());
assertSame(result, NONE);
assertTrue(Option.None.class.isInstance(result));
}
@Test
public void testGetOrElseForNone() {
Option<String> result = none();
assertSame(TEST_STRING, result.getOrElse(TEST_STRING));
}
@Test(expected=NoSuchElementException.class)
public void testGetDataFromNone() {
Option<String> result = none();
result.get();
fail();
}
@Test
public void testSome() {
Option<String> result = some(TEST_STRING);
assertTrue(result.isDefined());
assertFalse(result.isEmpty());
assertEquals(TEST_STRING, result.get());
assertTrue(Option.Some.class.isInstance(result));
}
@Test
public void testGetOrElseForSome() {
Option<String> result = some(TEST_STRING);
assertSame(TEST_STRING, result.getOrElse(null));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment