Skip to content

Instantly share code, notes, and snippets.

@RayStarkMC
Last active September 16, 2019 11:56
Show Gist options
  • Save RayStarkMC/b92751c631e725e51f2b85ad79e40de1 to your computer and use it in GitHub Desktop.
Save RayStarkMC/b92751c631e725e51f2b85ad79e40de1 to your computer and use it in GitHub Desktop.
JavaでKotlinのwhenライクなの書いてみたけど使いにくかったよ 素直に3項演算子やswitchを使おうと思ったよ
import java.util.Arrays;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
public final class When {
private When() {}
@SafeVarargs
public static <V, R> R when(V value, Function<V, R> defaultReturn, Pair<Predicate<V>, Function<V, R>>... matches) {
return Arrays.stream(matches)
.filter(match -> match.fst.test(value))
.findFirst()
.map(match -> match.snd)
.orElse(defaultReturn)
.apply(value);
}
@SafeVarargs
public static <V, R> R when(V value, Supplier<R> defaultReturn, Pair<Predicate<V>, Supplier<R>>... matches) {
return Arrays.stream(matches)
.filter(match -> match.fst.test(value))
.findFirst()
.map(Pair::snd)
.orElse(defaultReturn)
.get();
}
@SafeVarargs
public static <V> void whenStatement(V value, Consumer<V> defaultStatement, Pair<Predicate<V>, Consumer<V>>... matches) {
Arrays.stream(matches)
.filter(match -> match.fst.test(value))
.findFirst()
.map(Pair::snd)
.orElse(defaultStatement)
.accept(value);
}
public static void main(String[] args) {
//when, whenStatementの使用例
//型VにInteger型を使っているためオートボクシング、オートアンボクシングの問題があるが、今回は本質ではないので触れない
//FizzBuzz when Function version
for(int i=1; i<=15; i++) {
String j = when(i, Object::toString,
Pair.of(e -> e % 15 == 0, e -> "FizzBuzz"),
Pair.of(e -> e % 3 == 0, e -> "Fizz"),
Pair.of(e -> e % 5 == 0, e -> "Buzz")
);
System.out.println(j);
}
System.out.println();
//clamp when Supplier version
for(int i=0; i<10; i++) {
int in = i;
int k = when(in, () -> in,
Pair.of(e -> e < 3, () -> 3),
Pair.of(e -> 6 < e, () -> 6)
);
System.out.println(k);
}
System.out.println();
//2times whenStatement version
for(int i=0; i<10; i++) {
whenStatement(i, System.out::println,
Pair.of(e -> e % 2 == 0, e -> System.out.println(e + " multiple of 2")),
Pair.of(e -> e % 3 == 0, e -> System.out.println(e + " multiple of 3"))
);
}
}
public static class Pair<T1, T2> {
public final T1 fst;
public final T2 snd;
private Pair(T1 first, T2 second) {
fst = Objects.requireNonNull(first, "first must not be null.");
snd = Objects.requireNonNull(second, "second must not be null.");
}
public static <T1, T2> Pair<T1, T2> of(T1 first, T2 second) {
return new Pair<>(first, second);
}
public T1 fst() { return fst; }
public T2 snd() { return snd; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment