Created
July 6, 2013 02:50
-
-
Save poad/5938430 to your computer and use it in GitHub Desktop.
なんちゃってOptionモナド ref: http://qiita.com/poad1010/items/2435e3bc838e838f9a79
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
// 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); | |
} | |
} | |
} |
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
final Configuration config = new Configuration(); | |
final Option<String> opt = config.get("url"); | |
if (opt.just()) { | |
System.out.println(opt.get()); | |
} else { | |
// 値が無い場合の処理 | |
} |
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
// 受け取り側 | |
val conf = new Configuration() | |
conf.get("url") match { | |
case None => { | |
// 値が無い場合 | |
} | |
case Some(f) => { | |
// 値がある場合 | |
println(f) // fには、System.getProperty("url")の結果と同じものが入っている | |
} | |
} |
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
public class None<T> implements Option<T> { | |
public None() { | |
// do nothing | |
} | |
public T get() throws UnsupportedOperationException { | |
throw new UnsupportedOperationException(); | |
} | |
public boolean just() { | |
return false; | |
} | |
} |
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
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