Created
December 27, 2011 09:45
-
-
Save tototoshi/1523173 to your computer and use it in GitHub Desktop.
JavaでOption
This file contains 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
interface Function1<T, U> { | |
U apply(T t); | |
} | |
interface Optional<T> { | |
T get(); | |
T getOrElse(T defaultValue); | |
boolean isDefined(); | |
<U> Optional<U> map(Function1<T, U> f); | |
} | |
class Option<T> { | |
public static <T> Optional<T> apply(T value) { | |
if (value == null) { | |
return new None<T>(); | |
} else { | |
return new Some<T>(value); | |
} | |
} | |
} | |
class Some<T> implements Optional<T> { | |
private T value; | |
public Some(T value) { | |
this.value = value; | |
} | |
public T get() { | |
return value; | |
} | |
public T getOrElse(T defaultValue) { | |
return value; | |
} | |
public boolean isDefined() { | |
return true; | |
} | |
public <U> Optional<U> map(Function1<T, U> f) { | |
return Option.apply(f.apply(value)); | |
} | |
} | |
class None<T> implements Optional<T> { | |
public None() { | |
} | |
public T get() { | |
throw new java.util.NoSuchElementException(); | |
} | |
public T getOrElse(T defaultValue) { | |
return defaultValue; | |
} | |
public boolean isDefined() { | |
return false; | |
} | |
public <U> Optional<U> map(Function1<T, U> f) { | |
return new None<U>(); | |
} | |
} | |
public class Main { | |
public static void main(String[] args) { | |
Optional<String> s1 = Option.apply("foo"); | |
Optional<String> s2 = Option.apply(null); | |
System.out.println(s1.getOrElse("bar")); | |
System.out.println(s2.getOrElse("bar")); | |
Optional<String> s3 = Option.apply("3"); | |
Optional<Integer> i3 = | |
s3.map( | |
new Function1<String, Integer>() { | |
public Integer apply(String s) { | |
return Integer.parseInt(s); | |
} | |
} | |
).map( | |
new Function1<Integer, Integer>() { | |
public Integer apply(Integer i) { | |
return i * 100; | |
} | |
} | |
); | |
System.out.println(i3.get()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment