Can a java lambda have more than 1 parameter?

后端 未结 6 2081
渐次进展
渐次进展 2020-11-28 18:24

In Java, is it possible to have a lambda accept multiple different types?

I.e: Single variable works:

    Function  adder = i         


        
6条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 18:55

    It's possible if you define such a functional interface with multiple type parameters. There is no such built in type. (There are a few limited types with multiple parameters.)

    @FunctionalInterface
    interface Function6 {
        public Six apply(One one, Two two, Three three, Four four, Five five);
    }
    
    public static void main(String[] args) throws Exception {
        Function6, Character> func = (a, b, c, d, e) -> 'z';
    }
    

    I've called it Function6 here. The name is at your discretion, just try not to clash with existing names in the Java libraries.


    There's also no way to define a variable number of type parameters, if that's what you were asking about.


    Some languages, like Scala, define a number of built in such types, with 1, 2, 3, 4, 5, 6, etc. type parameters.

提交回复
热议问题