How to declare method's return type the as return type of last lambda in array passed to the method

前端 未结 3 592
清酒与你
清酒与你 2021-01-05 19:51

I ask for something which I see impossible and I\'ll delete question if it is.

I have got method:

public Object convertBy(Function... functions) {
}
         


        
3条回答
  •  一向
    一向 (楼主)
    2021-01-05 20:17

    Thank all of you who elaborated on the subject, your solutions are much better in real world.

    As the author I would like to post my solution that enabled not changing the invocations of convertBy() int the main() one bit. It is very short and ugly, but works.

    Main:

    Function> flines ... lambda here
    
    Function, String> join ... lambda here
    
    Function> collectInts ... lambda here
    
    Function, Integer> sum ... lambda here
    
    
    String fname = System.getProperty("user.home") + "/LamComFile.txt"; 
    InputConverter fileConv = new InputConverter<>(fname);
    List lines = fileConv.convertBy(flines);
    String text = fileConv.convertBy(flines, join);
    List 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 arglist = Arrays.asList(args);
    InputConverter> slistConv = new InputConverter<>(arglist);  
    sumints = slistConv.convertBy(join, collectInts, sum);
    System.out.println(sumints); 
    

    The InputConverter class:

    public class InputConverter {
    
        private T value;
    
        public InputConverter(T value) {
            this.value = value;
        }
    
        public  R convertBy(Function... functions) {
            Object result = value;
            for (int i = 0; i < functions.length; i++) {
                result = functions[i].apply(result);
            }
            return (R) result;
        }
    }
    

提交回复
热议问题