Java8 method reference used as Function object to combine functions

前端 未结 7 1609
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 15:02

Is there a way in Java8 to use a method reference as a Function object to use its methods, something like:

Stream.of(\"ciao\", \"hola\", \"hello         


        
7条回答
  •  死守一世寂寞
    2020-12-14 15:31

    You may also use

    Function.identity().andThen(String::length).andThen(n -> n * 2)
    

    The problem is, String::length is not necessarily a Function; it can conform to many functional interfaces. It must be used in a context that provides target type, and the context could be - assignment, method invocation, casting.

    If Function could provide a static method just for the sake of target typing, we could do

        Function.by(String::length).andThen(n->n*2)
    
    static  Function by(Function f){ return f; }
    

    For example, I use this technique in a functional interface

    static  AsyncIterator by(AsyncIterator asyncIterator)
    

    Syntax sugar to create an AsyncIterator from a lambda expression or a method reference.

    This method simply returns the argument asyncIterator, which seems a little odd. Explanation:

    Since AsyncIterator is a functional interface, an instance can be created by a lambda expression or a method reference, in 3 contexts:

     // Assignment Context
     AsyncIterator asyncIter = source::read;
     asyncIter.forEach(...);
    
     // Casting Context
     ((AsyncIterator)source::read)
         .forEach(...);
    
     // Invocation Context
     AsyncIterator.by(source::read)
         .forEach(...);
    

    The 3rd option looks better than the other two, and that's the purpose of this method.

提交回复
热议问题