java lambda 可以有 1 个以上的参数吗? [英] Can a java lambda have more than 1 parameter?

查看:17
本文介绍了java lambda 可以有 1 个以上的参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,是否可以让 lambda 接受多种不同的类型?

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

即:单变量工作:

    Function <Integer, Integer> adder = i -> i + 1;
    System.out.println (adder.apply (10));

可变参数也有效:

    Function <Integer [], Integer> multiAdder = ints -> {
        int sum = 0;
        for (Integer i : ints) {
            sum += i;
        }
        return sum;
    };

    //.... 
    System.out.println ((multiAdder.apply (new Integer [] { 1, 2, 3, 4 })));

但我想要一些可以接受许多不同类型参数的东西,例如:

But I want something that can accept many different types of arguments, e.g:

    Function <String, Integer, Double, Person, String> myLambda = a , b, c, d->  {
    [DO STUFF]
    return "done stuff"
    };

主要用途是为了方便起见,在函数内部有小的内联函数.

The main use is to have small inline functions inside functions for convenience.

我环顾了谷歌并检查了Java的功能包,但找不到.这可能吗?

I've looked around google and inspected Java's Function Package, but could not find. Is this possible?

推荐答案

如果你定义这样一个具有多个类型参数的函数式接口是可能的.没有这样的内置类型.(有几个具有多个参数的有限类型.)

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<One, Two, Three, Four, Five, Six> {
    public Six apply(One one, Two two, Three three, Four four, Five five);
}

public static void main(String[] args) throws Exception {
    Function6<String, Integer, Double, Void, List<Float>, Character> func = (a, b, c, d, e) -> 'z';
}

我在这里称它为Function6.名称由您决定,尽量不要与 Java 库中的现有名称冲突.

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.

某些语言,例如 Scala,定义了许多内置的此类类型,具有 1、2、3、4、5、6 等类型参数.

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

这篇关于java lambda 可以有 1 个以上的参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆