java - 无法将 ToIntBiFunction 作为 java lambda 表达式中的参数传递

标签 java lambda

我目前开始学习 Java 中的 Lambda 表达式,我试图找出为什么这段代码不起作用 我有一个普通类:

import java.util.function.ToIntBiFunction;


public class testclass {

    public testclass() {

    }
    public static ToIntBiFunction<Integer,Integer> multit2 = (Integer a,Integer b)->{
        return a*b;

    };

    public static Integer multit(Integer a, Integer b) {
        return a*b;
    }
}

以及另一个类中的main

public class ImageCovertor{

public static void main (String[] args) throws IOException {

    int d;
    testclass test = new testclass();

    BiFunction<ToIntBiFunction,Integer, Integer> ddd = (ToIntBiFunction fn, Integer a)->{
        return fn.applyAsInt(a,a);
    };
    d= ddd.apply(testclass::multit, 5);
    System.out.println(d);

}//end of main
public static ToIntBiFunction<Integer,Integer> multit = (Integer a,Integer b)->{
    return a*b;

};


}

我正在尝试将 multit 作为 ddd lambda 函数中的参数传递 但是这样的代码给了我一个错误:

d= ddd.apply(testclass::multit, 5);

类型 testclass 没有定义适用于此的 multit(Object, Object)

也尝试在主函数中创建该函数,但它给了我同样的错误 当我编写代码时,代码可以工作

testclass.multit

而不是

testclass::multit

有人可以向我解释为什么第二个不起作用以及如何解决这个问题吗? 谢谢

最佳答案

testclass::multit 表示属于 testclass 的方法 multit。您拥有的是一个包含函数的字段 testclass.multit 。保存函数的字段与方法不同。

class MyClass {
    // This is a method, `MyClass::foo`
    public static Integer foo(Integer a, Integer b) {
        return a*b;
    }
    // This is a field holding a function, `MyClass.bar`
    public static ToIntBiFunction<Integer, Integer> bar = (Integer a,Integer b)-> {
        return a*b;
    };
}

关于java - 无法将 ToIntBiFunction 作为 java lambda 表达式中的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50299328/

相关文章:

java - 使用 Spring-Security 实现 HttpSessionLister 时出现问题

c++ - lambda 采用 `char` 参数

java - 在java中生成新变量

java - 无法显示 Java 中查询的搜索结果

c# - 如何在 LINQ 语句中重用表达式?

python - 使用带有两个参数的 lambda 函数映射的 Spark RDD 有什么问题?

ruby - 在 RSpec 中期待 Lambda

python - f = lambda n :(1, f(n-1)*n)[n>1] 在 Python 3 中给出 RunTimeError

java - 报表任务管理器中的processedWithError是什么意思?

java - HTTPPOST 返回 404 ANDROID