kotlin 将函数作为参数传入调用,比如::

kotlin的高阶用法,可以将函数作为参数传入另一个函数内调用,

1、使用  ::   传入函数,带参数和返回值的函数,比如:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        // TODO: Use the ViewModel

        // 传入函数参数
        printFather(::printSon, "father")
    }

    /**
     * 定义一个函数参数
     */
    private fun printFather(method: (String) -> String, str: String) {
        Log.d("Alex", str)
        Log.d("Alex", method("son"))
        // 调用函数的invoke()是一样的
        Log.d("Alex", method.invoke("son"))
    }

    private fun printSon(str: String): String {
        return str
    }

打印结果:

2023-04-11 08:56:58.273 22645-22645 Alex                    com.example.myapplication2           D  father
2023-04-11 08:56:58.273 22645-22645 Alex                    com.example.myapplication2           D  son
2023-04-11 08:56:58.273 22645-22645 Alex                    com.example.myapplication2           D  son
 

使用  ::   传入函数,不带参数和返回值的函数,比如:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        // TODO: Use the ViewModel

        // 传入函数参数
        printFather(::printSon, "father")
    }

    /**
     * 定义一个函数参数
     */
    private fun printFather(method: () -> Unit, str: String) {
        Log.d("Alex", str)
        method()
        // 调用函数的invoke()是一样的
        method.invoke()
    }

    private fun printSon() {
        Log.d("Alex", "son")
    }

打印结果:

2023-04-11 08:52:54.065 22542-22542 Alex                    com.example.myapplication2           D  father
2023-04-11 08:52:54.065 22542-22542 Alex                    com.example.myapplication2           D  son
2023-04-11 08:52:54.065 22542-22542 Alex                    com.example.myapplication2           D  son
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值