Search code examples
javagenericsfunctional-interface

Variable (Function type) argument count and variable return type


I have the following question- I have to write one method, which will take variable amount of Function arguments and, based on that, will return the needed type. The problem is, that the functions from arguments are run in order:

public class Main {
    public static void main(String[] args) throws Exception {

    //Lambda expressions which will be taken as arguments in method.

    Function<String,List<String>> flines = e->{
    };
    Function<List<String>,String> join = e ->{
    };
    Function<String,List<Integer>> collectInts = e->{
    };
    Function<List<Integer>,Integer> sum = e->{
    };

    // end of lambdas

    String fname = System.getProperty("C:/LamComFile.txt"); 
    InputConverter<String> fileConv = new InputConverter<>(fname);
    List<String> lines = fileConv.convertBy(flines);
    String text = fileConv.convertBy(flines, join);
    List<Integer> ints = fileConv.convertBy(flines, join, collectInts);
    Integer sumints = fileConv.convertBy(flines, join, collectInts, sum);

    System.out.println(lines);
    System.out.println(text);
    System.out.println(ints);
    System.out.println(sumints);

    List<String> arglist = Arrays.asList(args);
    InputConverter<List<String>> slistConv = new InputConverter<>(arglist);  
    sumints = slistConv.convertBy(join, collectInts, sum);
    System.out.println(sumints);

    }
}

As You can see, I need to create a class, which will have one method (overloading is not allowed) and based on what that method will receive, it has to return the correct type.

I have the beginning of the InputConverter class, but I have no idea how can make the next Functions get the arguments from the ones before.

  public class InputConverter<T> {
      private T obj;

      public InputConverter(T obj) {
           this.obj = obj;
      }

      public <what goes here?> and_here convertBy(Function<In,Out>... funcs){

      }
  }

I assume that I can do something like this?

if(funcs.length()==1){
    what? = funcs[0].apply(this.obj);
    return what?
}

Solution

  • You can't express that in Java's type system. Accept the need for something else. For example, you could just write f1.andThen(f2).andThen(f3).andThen(f4)....