Kotlin多参数回调

1、单个参数回调:

        /**
         * 单个返回值调用
         */
        checkUserStatus("小明"){
            Log.d("LUO","---:$it")
        }
   //被调用的方法
   fun checkUserStatus(name:String?=null,result:((str:String)->Unit)){
        result.invoke("你好啊")
    }

2、多个参数回调:

  /**
         * 中间多个返回值调用
         */
        checkUserData("123", finishBlock = {
           Log.d("LUO","--finishBlock--")
        }, closedBlock = {
           Log.d("LUO","--closedBlock--")
        }, errorBlock = {
            Log.d("LUO","--errorBlock--")
        }, src = R.drawable.ic_launcher_background)
   //被调用的方法
    fun checkUserData(
        id: String?,
        from: String? = null,
        extra: Bundle? = null,
        finishBlock: (() -> Unit)? = null,
        closedBlock: (() -> Unit)? = null,
        errorBlock: ((e: Exception) -> Unit)? = null,
        src: Int
    ) {
        finishBlock?.invoke()
        closedBlock?.invoke()
        errorBlock?.invoke(Exception())
    }

3、java中调用Kotlin的回调

1、java中调用Kotlin回调

public class UserActivity extends AppCompatActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);

        /**
         * java中调用Kotlin回调
         */
        CommonUtils.INSTANCE.clickItime("小刚", new Function1() {
            @Override
            public Unit invoke(String str) {
                Log.d("LUO","===返回:"+str);//===返回:小刚: 回来了
                return null;
            }
        });
    }
}

2、Kotlin接口回调

object CommonUtils {
    /**
     * Kotlin接口回调
     */
    fun clickItime(name:String?=null,result:((str:String)->Unit)){
        result.invoke("${name}: 回来了")
    }
}

你可能感兴趣的:(Kotlin多参数回调)