Manuel Dossinger
10/13/2021, 7:54 PMfun foo(a: Type1, b: Type2, c: Type3): Type4
val result: Type4? = foo(myA?, myB?, myC?) // is null if any of the parameters is null
Grégory Lureau
10/13/2021, 7:58 PM@Contract("null, null, null -> null") fun foo(...)
Manuel Dossinger
10/13/2021, 8:01 PMephemient
10/13/2021, 8:01 PMval result = if (myA != null && myB != null && myC != null) {
foo(myA, myB, myC)
} else null
val result = run {
foo(myA ?: return@run null, myB ?: return@run null, myC ?: return@run null)
}
Grégory Lureau
10/13/2021, 8:01 PMfoo
method completely?
Looks weird to me, the nullability of args as nothing to do with calling the method, even if I suppose there is some cases where you would want to do that. Also you could do a weird ?.let
embedded checks or just a simple if (mA!= null && myB != null..)
ephemient
10/13/2021, 8:01 PMCasey Brooks
10/13/2021, 8:02 PM.any { it == null }
.
An easier-to-understand solution might just be to use precondition checks at the start of the function on each parameter
fun foo(a: Type1?, b: Type2?, c: Type3?): Type4? {
if(a == null) return null
if(b == null) return null
if(c == null) return null
// at this point, all parameters have been smart-cast to non-null
return Type4(a.toString() + b.toString() + c.toString())
}
Manuel Dossinger
10/13/2021, 8:10 PMTobias Suchalla
10/14/2021, 6:33 AMfun <P1, P2, P3, R> runOrNull(
param1: P1?,
param2: P2?,
param3: P3?,
block: (P1, P2, P3) -> R
): R? {
return block(
param1 ?: return null,
param2 ?: return null,
param3 ?: return null
)
}
fun foo(a: Type1, b: Type2, c: Type3): Type4
val result: Type4? = runOrNull(myA, myB, myC, ::foo)
ephemient
10/14/2021, 6:39 AMlet
-like than run
-like and would make sense to inline
but yeah, things of that nature have been thrown around before (e.g. https://github.com/stupacki/MultiFunctions)