So we have a interface, called Func.java, that looks like this:
public interface Func<A,B> {
public B apply(A x);
}
Then we have the main class, called mainClass.java, which looks like this:
public class mainClass{
public static void main(String[] args) {
}
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(A x){
return g.apply(f.apply(x));
}
};
}
}
I am not really sure then how to call this compose method in the main method, and how this code actually compiles! I mean, are the java generics necessary here for this to work?
Here is how you can call compose:
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"));
}
}
I'm not quite sure what you're asking as far as generics being necessary. In the literal sense, no, they are not. Java generics just give you type safety. You could certainly scrap them completely and change A, B, and C to just be Objects instead. However, if you want to explicitly define the types being used, like in my example with String, Integer, and Double, then yes, you need to use generics in this case.
public class FirstClassFunction {
interface Func< A, B > {
public B apply( A x );
}
static <A, B, C>
Func< A, C > compose( final Func< A, B > f, final Func< B, C > g ) {
return new Func< A, C >() {
@Override public C apply( A x ) {
return g.apply( f.apply( x ) );
}};
}
public static void main( String[] args ) {
Func< Double, Character > f =
new Func< Double, Character >(){
@Override public Character apply( Double x ) {
return 'a';
}};
Func< Character, String > g =
new Func< Character, String >(){
@Override public String apply( Character x ) {
return "Hello";
}};
Func< Double, String > c = compose( f, g );
System.out.println( c.apply( 3.14 ));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With