我有一个界面:
interface A{
fun test(foo:Int,bar:Int)
}
我有一个对 A 实现的可空引用
val aImpl:A? = .....
然后我有一个高阶函数,它接收一个与测试相同的可空签名函数
...
fun higherOrder(f:((a:Int,B:Int)-> Unit)?){ ... }
如何将测试函数的引用传递给 higherOrder?例如,这不起作用:
higherOrder(aImpl::test) // aImpl is nullable
higherOrder(aImpl?::test) // I'd expect reasonably this to work, but syntax is invalid
这行得通,但感觉有点笨拙和冗长。我试图避免额外的 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) }
关于kotlin - 惯用地传递可空类型的方法引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57573364/