[英]Passing a method reference of a nullable type idiomatically
我有一个界面:
interface A{
fun test(foo:Int,bar:Int)
}
我对 A 的实现有一个可为空的引用
val aImpl:A? = .....
然后我有一个高阶函数,它接收一个与测试相同的签名的可为空函数
...
fun higherOrder(f:((a:Int,B:Int)-> Unit)?){ ... }
如何将测试函数的引用传递给 highOrder? 例如,这不起作用:
higherOrder(aImpl::test) // aImpl is nullable
higherOrder(aImpl?::test) // I'd expect reasonably this to work, but syntax is invalid
这有效,但感觉有点hacky和漫长。 我试图避免额外的 lambda。
higherOrder(aImpl?.let{it::test})
有没有更惯用的方法来做到这一点?
正如评论中提到的,有几种方法可以做到这一点
interface A{
fun test(foo:Int,bar:Int)
}
val aImpl:A? = .....
fun higherOrder(f:((a:Int,B:Int)-> Unit)?){ ... }
// Not very Kotlin
if (aImpl != null) higherOrder(aImpl::test)
// Kotlin, but weird
higherOrder( aImpl?.let { it::test } )
// Very kotlin, maybe a bit more overhead in understanding
higherOrder { a, b -> aImpl?.test(a, b) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.