Kotlin:函数参数发送但不执行?
我有以下代码传入一个整数和两个函数。
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时,我希望它敬酒hello1
和hello-again1
。 当它是1时,我希望它敬酒hello-again2
, hello-again2
。
但是,当我运行该函数时,它只会敬酒hello-again1
或hello-again2
。 发送功能根本没有被激活。 我错过了什么?
你忘了实际用()
调用你的lambdas:
... action1() Toast.makeText(ctx, "hello-again1", Toast.LENGTH_SHORT).show() ...
有关为什么需要调用lambda的更多信息:不能比@hotkey做得更好。