Skip to content

Instantly share code, notes, and snippets.

@poad
Created July 6, 2013 02:50
Show Gist options
  • Save poad/5938430 to your computer and use it in GitHub Desktop.
Save poad/5938430 to your computer and use it in GitHub Desktop.
なんちゃってOptionモナド ref: http://qiita.com/poad1010/items/2435e3bc838e838f9a79
// Option型(Optionモナド)を返す側
public class Configuration {
public Option<String> get(String key) {
final String value = System.getProperty(key);
if (value == null) {
return new None<String>();
} else {
return new Some<String>(value);
}
}
}
final Configuration config = new Configuration();
final Option<String> opt = config.get("url");
if (opt.just()) {
System.out.println(opt.get());
} else {
// 値が無い場合の処理
}
// 受け取り側
val conf = new Configuration()
conf.get("url") match {
case None => {
// 値が無い場合
}
case Some(f) => {
// 値がある場合
println(f) // fには、System.getProperty("url")の結果と同じものが入っている
}
}
public class None<T> implements Option<T> {
public None() {
// do nothing
}
public T get() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
public boolean just() {
return false;
}
}
public class Some<T> implements Option<T> {
private final T value;
public Some(T value) {
this.value = value;
}
public T get() {
return this.value;
}
public boolean just() {
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment