gpt4 book ai didi

lambda - 如何检查参数是否为 lambda

转载 作者:行者123 更新时间:2023-12-02 13:37:59 29 4
gpt4 key购买 nike

我正在处理 MyCustomType 的实例集合如下:

fun runAll(vararg commands: MyCustomType){
commands.forEach { it.myMethod() }
}

除了 MyCustomType 的实例,我想传递和处理 () -> Unit 类型的 lambdas ,像这样:
fun runAll(vararg commands: Any){
for(command in commands){
if (command is MyCustomType){
command.myMethod()
} else
if(command is () -> Unit){
command.invoke()
}
}
}

if(command is () -> Unit){编译时出现以下消息: Cannot check for instance of erased type: () -> Unit .

有没有办法检查一个对象是否是 () -> Unit在运行时?

我看过 another answer that recommends using wildcards .我认为这无关紧要:我的代码不使用泛型。

最佳答案

Kotlin 会将您的 lambda 编译为 Function0 的实例.如果您知道这一点,您可以使用 when block 进行比较和智能转换非常好:

fun runAll(vararg commands: Any) {
commands.forEach {
when(it) {
is Function0<*> -> it.invoke()
is MyCustomType -> it.myMethod()
}
}
}

然后调用它:
fun main(args: Array<String>) {
runAll(
MyCustomType(),
{ println("Lambda!") }
)
}

警告 : 这种方法的缺点是使用类型删除,你不知道你是否得到一个 Function0<Unit>Function0<Int> ,因为该类型在运行时不可用,您无法做出决定。这意味着有人可以给你一个返回某些东西的 lambda,而你会忽略结果。

关于lambda - 如何检查参数是否为 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51708709/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com