【发布时间】:2018-08-06 13:23:53
【问题描述】:
我正在处理MyCustomType 的实例集合,如下所示:
fun runAll(vararg commands: MyCustomType){
commands.forEach { it.myMethod() }
}
除了 MyCustomType 的实例之外,我还想传递和处理 () -> Unit 类型的 lambda,如下所示:
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。我认为这无关紧要:我的代码不使用泛型。
【问题讨论】: