java - 将 lambda 函数存储在变量中?

标签 java lambda java-8

众所周知,在 java-8 中我们可以将函数/方法存储在变量中。通过使用以下方式。

    @FunctionalInterface
    public interface MyInterface {

      public string getValue(int val1, int val2);

    }


    public class MyClass {

    static String someFun(int val1, int val2) {
       return ""+(val1+val2)

    }

     static BiFunction<Integer, Integer, String> testParamFun = (a,b) -> ""+(a+b);

    public static void main(String[] args){

       MyInterface intr = MyClass::someFun;
       System.out.println(int.getValue(2,4)); // outpur will be "6" 

       /* i want this, but it give me compile time error? 
         I want to store that function in variable like i was doing in above case. */

   MyInterface inter = MyClass::testParamFun;
   System.out.println(inter.getValue(4,5)); // it gives me error.
   // then i tried this
   System.out.println(inter.apply(4,5)); // i got error again. 


    }

    }

我的问题是,如何将 BiDirection 存储在变量类型 MyInterface

最佳答案

需要引用BiFunction的方法:

MyInterface int_ = MyClass.testParamFun::apply;

关于java - 将 lambda 函数存储在变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32521445/

相关文章:

java - 为什么子类继承自基类的方法不能打印自身字段的值?

java - 多流操作

Python单行 "for"表达式

java - 使用流和 lambda 将 Map<Integer, List<String>> 展平为 Map<String, Integer>

JavaFX ColorPicker NullPointerException

java - 没有分隔符的本地日期解析不起作用

Java swing 选项卡式 Pane 添加选项卡异常

Java构造函数在不同类中的使用

java - 检查字符串是否是回文

lambda - Kotlin lambda 中的 vararg 参数