仅当所有参数都不为null时,Kotlin调用函数 [英] Kotlin call function only if all arguments are not null
问题描述
如果所有(或某些)参数为null,kotlin中是否有一种方法可以防止函数调用?例如具有功能:
Is there a way in kotlin to prevent function call if all (or some) arguments are null? For example Having function:
fun test(a: Int, b: Int) { /* function body here */ }
在参数为null
的情况下,我想防止进行空检查.例如,对于参数:
I would like to prevent null checks in case when arguments are null
. For example, for arguments:
val a: Int? = null
val b: Int? = null
我想替换:
a?.let { b?.let { test(a, b) } }
具有:
test(a, b)
我想函数定义语法可能看起来像这样:
I imagine that function definition syntax could look something like this:
fun test(@PreventNullCall a: Int, @PreventNullCall b: Int)
那等同于:
fun test(a: Int?, b: Int?) {
if(a == null) {
return
}
if(b == null) {
return
}
// function body here
}
这样(或类似的东西)是否可以减少调用者(可能是函数作者)的冗余代码?
Is something like that (or similar) possible to reduce caller (and possibly function author) redundant code?
推荐答案
如果您不希望调用者自己进行这些检查,则可以在中介函数中执行空检查,然后在出现以下情况时调用真正的实现:他们通过了:
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.
这篇关于仅当所有参数都不为null时,Kotlin调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!