How to overload a method by method with parameters list that contains parameters of the exact same type but parametrized with other types

前端 未结 1 1703
天涯浪人
天涯浪人 2021-01-07 11:45

I have a methods:

public List convertBy(Function> flines, Function, String> join, Fu         


        
1条回答
  •  广开言路
    2021-01-07 12:51

    If you want to create a method which applies multiple functions and is not interested in the intermediate values, you can make it a generic method. The code in your question is strange as it assumes that value can be a String and a List at the same time.

    But comparing with your other question, there’s a different picture. While the varargs method there can’t work that way, you can easily provide overloaded methods for the actual use cases:

    public class InputConverter {
    
        private T value;
    
        public InputConverter(T value) {
            this.value = value;
        }
        public  R convertBy(Function f) {
            return f.apply(value);
        }
        public  R convertBy(
            Function f1, Function f2) {
            return f2.apply(f1.apply(value));
        }
        public  R convertBy(
            Function f1, Function f2,
            Function f3) {
            return f3.apply(f2.apply(f1.apply(value)));
        }
        public  R convertBy(
            Function f1, Function f2,
            Function f3, Function f4) {
            return f4.apply(f3.apply(f2.apply(f1.apply(value))));
        }
    }
    

    Assuming that you fixed your interface types and created functions as described in this answer, you can use it like

    InputConverter fileConv=new InputConverter<>("LamComFile.txt");
    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);
    

    0 讨论(0)
提交回复
热议问题