Created
May 24, 2013 12:42
-
-
Save xuwei-k/5643241 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// b88 にて、直接コマンドラインから javac と java を呼び出して動作を確認 | |
import java.util.Optional; | |
import java.util.function.Function; | |
final class OptionalUtil{ | |
public static <A, B> Optional<B> bind(Optional<A> o, Function<A, Optional<B>> f){ | |
return o.isPresent() ? f.apply(o.get()) : Optional.empty(); | |
} | |
} | |
final class Main{ | |
// java8的には、OptionalIntが用意されてるらしいので、本当はそっちの使用の検討も必要(bindもそれぞれ用意?) | |
static final Optional<Integer> string2int(final String s){ | |
try{ | |
return Optional.of(Integer.parseInt(s)); | |
}catch(NumberFormatException e){ | |
return Optional.empty(); | |
} | |
} | |
public static void main(String[] args){ | |
final Optional<String> some1 = Optional.of("123"); | |
final Optional<String> some2 = Optional.of("hoge"); | |
final Optional<String> none = Optional.empty(); | |
// Optional[123] | |
System.out.println( | |
OptionalUtil.bind(some1, Main::string2int) | |
); | |
// Optional.empty | |
System.out.println( | |
OptionalUtil.bind(some2, Main::string2int) | |
); | |
// Optional.empty | |
System.out.println( | |
OptionalUtil.bind(none, Main::string2int) | |
); | |
// もちろん、直接リテラルでlambdaを書いても可能 | |
// ラムダの引数の型の推論まで効くらしい。 | |
// Scalaと違い try catch が文なので、ラムダ内でreturnが必要なのが残念 | |
// Optional.empty | |
System.out.println( | |
OptionalUtil.bind(some1, s -> { | |
try{ | |
return Optional.of(Integer.parseInt(s)); | |
}catch(NumberFormatException e){ | |
return Optional.empty(); | |
} | |
}) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why is your annotation Japanese?Can you mark them with English?