更新时间:2023-11-30 23:03:40
如果您不希望调用者自己进行这些检查,则可以在中介函数中执行空检查,然后在出现以下情况时调用真正的实现:他们通过了:
If you don't want callers to have to do these checks themselves, you could perform null checks in an intermediary function, and then call into the real implementation when they passed:
fun test(a: Int?, b: Int?) {
a ?: return
b ?: return
realTest(a, b)
}
private fun realTest(a: Int, b: Int) {
// use params
}
这是@Alexey Romanov在下面提出的功能的实现:
here's an implementation of the function @Alexey Romanov has proposed below:
inline fun <T1, T2, R> ifAllNonNull(p1: T1?, p2: T2?, function: (T1, T2) -> R): R? {
p1 ?: return null
p2 ?: return null
return function(p1, p2)
}
fun test(a: Int, b: Int) {
println("$a, $b")
}
val a: Int? = 10
val b: Int? = 5
ifAllNonNull(a, b, ::test)
如果需要其他功能,当然需要为2、3等参数实现ifAllNonNull
功能.
Of course you'd need to implement the ifAllNonNull
function for 2, 3, etc parameters if you have other functions where you need its functionality.