Skip to content

Instantly share code, notes, and snippets.

@mt-village
Last active April 21, 2017 04:02
Show Gist options
  • Save mt-village/693bc0948e37745dd337432956b99b70 to your computer and use it in GitHub Desktop.
Save mt-village/693bc0948e37745dd337432956b99b70 to your computer and use it in GitHub Desktop.
if文でも三項演算子でもない第三のIf文を書いてみる ref: http://qiita.com/mt-village/items/7d1b5560224d2675d770
String s = null;
if (testSomeCond()) {
s = "is true";
} else {
s = "is false";
}
doSomething(s);
String s = testSomeCond() ? "is true" : "is false";
doSomething(s);
String s = If.correct(testSomeCond()).then("is true").orElse("is false");
doSomething(s);
String s = If.correct(testSooooooooooooooooooooooooooooooooomething())
.then("is trueeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
.orElse("is falseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
doSomething(s);
public class If {
public static BoolSaver correct(Boolean b) {
return () -> b;
}
}
@FunctionalInterface
public interface BoolSaver {
Boolean get();
default <A> Else<A> then(A a1) {
return (A a2) -> get() ? a1 : a2;
}
}
@FunctionalInterface
public interface Else<A> {
A orElse(A a2);
}
int[] a = {1,2};
int i = 3;
int result = If.correct(i < a.length).then(a[i]).orElse(-1);
int[] a = {1,2};
int i = 3;
// 通常の書き方
int a = If.correct(i < a.length).then(a.length).orElse(i);
// 戻り値の片方が例外を発生し得る場合の書き方
int b = If.correct(i < a.length)
.then(() -> a[i])
.orElse(() -> -1);
public class If {
public static BoolSaver correct(Boolean b) {
return () -> b;
}
}
@FunctionalInterface
public interface BoolSaver {
Boolean get();
default <A> Else<A> then(A a1) {
return (A a2) -> get() ? a1 : a2;
}
default <A> ElseSaver<A> then(Supplier<A> a1) {
return (Supplier<A> a2) -> get() ? a1.get() : a2.get();
}
}
@FunctionalInterface
public interface Else<A> {
A orElse(A a2);
}
@FunctionalInterface
public interface ElseSaver<A> {
A orElse(Supplier<A> a2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment