Kotlin:发送但未执行的函数参数?

时间:2016-04-09 02:24:14

标签: kotlin

我有以下代码传递一个Integer和两个函数。

choseNavigation(childPos, {Toast.makeText(ctx, "hello1", Toast.LENGTH_SHORT).show()},
                                {Toast.makeText(ctx, "hello2", Toast.LENGTH_SHORT).show()})

功能定义如下:

private fun choseNavigation(pos: Int, action1: () -> Unit, action2: () -> Unit) {
    when(pos) {
        0-> {
            action1
            Toast.makeText(ctx, "hello-again1", Toast.LENGTH_SHORT).show()
        }
        1->{
            action2
            Toast.makeText(ctx, "hello-again2", Toast.LENGTH_SHORT).show()
        }
    }
}

当我的childPost为0时,我希望它为Toast hello1hello-again1。当它为1时,我希望它为Toast hello2hello-again2

但是,当我运行该功能时,它只会举杯hello-again1hello-again2。发送功能根本没有被激活。我错过了什么吗?

1 个答案:

答案 0 :(得分:3)

你忘了用()实际调用你的lambdas:

...
action1()
Toast.makeText(ctx, "hello-again1", Toast.LENGTH_SHORT).show()
...

有关为什么需要调用lambda的其他信息:无法比@hotkey did更好地解释它。

相关问题