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 bo
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
}
Edit: here's an implementation of the function @Alexey Romanov has proposed below:
inline fun 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)
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.