예 :
정수 (B
)에 문자열 (A
)을 변환하는 Func<A,B>
.
class Converter implements Func<String, Integer> {
@Override
public Integer apply(String x) {
// System.out.println("Converter converting String \"" + x + "\" to an Integer");
return Integer.valueOf(x);
}
}
문자열 (B
) 정수 (A
)를 변환하여 다른 Func<A,B>
구현, 즉 그 Strig
class Binary implements Func<Integer, String> {
@Override
public String apply(Integer x) {
// System.out.println("Binary converting Integer " + x + " to binary String");
return Integer.toBinaryString(x);
}
}
의 이진 표현을 보여주는 main
방법을 나타낸다.
public static void main(String[] args) {
// compose those to functions and you can convert strings representing
// numbers (base 10) to Strings that represent the same number (base 2)
Func<String, String> binaryStringConverter = compose(new Converter(), new Binary());
System.out.println(binaryStringConverter.apply("123"));
}
더 나은 당신이
System.out.println()
제표의 주석을 해제하고 코드를 실행할 수 있습니다 무슨 일이 일어나고 있는지 이해합니다.
public class mainClass {
public static <A, B, C> Func<A, C> compose(final Func<A, B> f, final Func<B, C> g) {
return new Func<A, C>() {
public C apply(final A x) {
return g.apply(f.apply(x));
}
};
}
public static void main(final String[] args) {
Func<String, Double> toDouble = new Func<String, Double>() {
public Double apply(final String x) {
return Double.parseDouble(x);
}
};
Func<Double, Integer> toInt = new Func<Double, Integer>() {
public Integer apply(final Double x) {
return (int) x.doubleValue();
}
};
Func<String, Integer> composed = compose(toDouble, toInt);
System.out.println("Composed: " + composed.apply("1.23"));
}
}
난 당신이 제네릭이 필요한 것으로까지 요구하고 무엇을 아주 확실하지 않다 : 여기
컴파일 해 보셨습니까? –