有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在变量中存储lambda函数?

正如我们所知,在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


共 (1) 个答案

  1. # 1 楼答案

    您需要参考BiFunction的方法:

    MyInterface int_ = MyClass.testParamFun::apply;