Kotlin的函数的参数可以直接传递方法,Java不能,需要通过定义接口,用接口的方式传递。
但是Java和Kotlin又可以互调,那如果我们再kotlin的类中定义一个需要参数传方法的函数,然后java去调用它这个函数,会以怎么样的形式传给它呢?
我们在kotlin文件中定义一个函数,这个函数需要传递一个字符串和一个方法,这个方法需要传递两个数字,并且返回一个数字:(为方便调用声明为object,相当于java里面的静态类吧,里面的方法都是可直接访问)
object TestKotlin{
fun testKotlin(testStr:String,testFunReturnStr:(Int,Int)-> Int) : String{
return testStr + testFunReturnStr(1,2)
}
}
我们在另一个kotlin文件中调用这个方法:
//先提供一个方法待会作为参数传递
private fun testFunAdd(one:Int, two:Int):Int{
return one + two
}
//然后调用第一步那里写的测试方法
var re = TestKotlin.testKotlin("加法得到:",this::testFunAdd)
输出的这个re结果就是:
加法得到:3
我们发现其实这个传递方法this::testFunAdd不就是java1.8里面那个landau表达式嘛,是的,我们java里面也可以这么传:
//提供一个方法待会传递
public int javaFun(int one, int two) {
return one + two;
}
//然后调用kotlin里面的方法:
TestKotlin.INSTANCE.testKotlin("加法得到:", this::javaFun)
但是我们使用landau表达式是知道它具体什么匿名内部类转换过来的,这个我们不知道,所以就取消这种方式,自己探索原表达式应该是怎么样的:
TestKotlin.INSTANCE.testKotlin("加法得到:",fun);
这个fun我不知道什么类型,所以先定义一个变量名称,然后通过代码提示自动生成一个变量声明:
Function2<? super Integer, ? super Integer, Integer> fun;
TestKotlin.INSTANCE.testKotlin("加法得到:",fun);
是一个叫做Function2的对象,那这个Function2怎么实现呢?按照我们没有对象就new一个对象的思路,我们给它new一下:
Function2<? super Integer, ? super Integer, Integer> fun = new Function2<Integer, Integer, Integer>() {
@Override
public Integer invoke(Integer integer, Integer integer2) {
}
};
这样一看就很明了了,我们就是实现这个invoke方法就相当于是传过去的方法:
Function2<? super Integer, ? super Integer, Integer> fun = new Function2<Integer, Integer, Integer>() {
@Override
public Integer invoke(Integer integer, Integer integer2) {
return integer + integer2;
}
};
结论:
实际上,这么个传递方式其实也就是java里面的实现接口方式:
我们追进Function2源码去,可以看到是kotlin定义的根据参数个数从Function0到Function22的接口。
其他类似的哪一边特有的我觉得kotlin在设计之初也都考虑好了,既然可以互调那肯定是会给我们提供对应的解决方案。