Java的接口回调
在Java当中,使用接口回调的形式传递数据很常见,定义接口,声明接口,在A类中传入接口的实例对象,就可以接收传入的数据index.而在kotlin中,比较简单,传入一个函数即可
public class B {
void testClick(){
if (iUpdateListener!=null){
iUpdateListener.updateItem(9);
}
}
IUpdateListener iUpdateListener;
public void setiUpdateListener(IUpdateListener iUpdateListener) {
this.iUpdateListener = iUpdateListener;
}
interface IUpdateListener{
void updateItem(int index);
}
}
public class A {
void testMethod(){
B b = new B();
b.setiUpdateListener(new B.IUpdateListener() {
@Override
public void updateItem(int index) {
//TODO 接收调用的地方
}
});
}
}
kotlin高阶函数
先说下高级函数的结构,kotlin函数一等公民,可以由引用来代表一个函数。
imageLoader: ((T, ImageView) -> Unit)
imageLoader函数的引用对象(T,ImageView)当前函数的参数,T是泛型->Unit这部分就是函数的返回值
使用:
fun setDataList(
dataList: List,
imageLoader: ((T, ImageView) -> Unit) ) {
调用高阶函数,传入参数即可,就会回调到A类的函数体
this.imageLoader(dataList[position], mImageView)
}
文章为作者独立观点,不代表股票交易接口观点