Ahmed Hassan
11/30/2021, 10:41 PMnullableVarParent?.let { nonNullParent ->
if (
nonNullParent.nullableValChildOne == null
|| nonNullParent.nullableValChildTwo == null
)
return
funcEx(
nonNullParent.nullableValChildOne,
nonNullParent.nullableValChildTwo
)
}
2nd Block
if (
nullableVarParent?.nullableValChildOne == null
|| nullableVarParent?.nullableValChildTwo == null
)
return
funcEx(
nullableVarParent?.nullableValChildOne!!,
nullableVarParent?.nullableValChildTwo!!
)
Some would think the second one is safe too because of the if condition, but is it better to use?
Appreciate your support.Lilly
11/30/2021, 11:54 PMfun <T : Any, R : Any> whenAnyNotNull(vararg options: T?, block: (List<T>) -> R) {
if (options.any { it != null }) {
block(options.filterNotNull())
}
}
use it like:
whenAnyNotNull(nullableVarParent?.nullableValChildOne, nonNullParent.nullableValChildTwo) { (a, b) ->
funcEx(a, b)
} ?: return
Lilly
11/30/2021, 11:55 PMfun <T : Any, R: Any> whenAllNotNull(vararg options: T?, block: (List<T>) -> R): R? {
if (options.all { it != null }) {
return block(options.filterNotNull()) // or do unsafe cast to non null collection
}
return null
}
whenAllNotNull(nullableVarParent?.nullableValChildOne, nonNullParent.nullableValChildTwo) { (a, b) ->
funcEx(a, b)
} ?: return
Aidan Low
12/01/2021, 1:49 AMnullableVarParent?.nullableValChildOne?.let { nonNullChildOne ->
nullableVarParent?.nullableValChildTwo?.let { nonNullChildTwo ->
funcEx(nonNullChildOne, nonNullChildTwo
}
}
though it’s not very readable. Honestly it might be simplest to just say
funcEx(
nullableVarParent?.nullableValChildOne ?: return,
nullableVarParent?.nullableValChildTwo ?: return
)
Ahmed Hassan
12/01/2021, 9:40 AMLilly
12/01/2021, 9:55 AMAidan Low
12/01/2021, 5:17 PM