Matias Reparaz
04/02/2025, 6:02 PM!!
is necessary in the second branch of the when
expression in this code? Isn’t there enough information for a smart cast to a non-nullable type?
fun checkSomething(old: Something?, new: Something?): Something = when {
old == null && new == null -> throw IllegalArgumentException("Both old and new arguments are null")
old == null -> new!!
new == null -> old
else -> old
}
Vampire
04/02/2025, 6:05 PMephemient
04/02/2025, 6:20 PMwhen {
old != null -> old
new != null -> new
else -> throw IllegalArgumentException("Both old and new arguments are null")
}
or of course simply
requireNotNull(old ?: new)
perhaps your real use case is more complex?Matias Reparaz
04/02/2025, 6:31 PMfun checkSomething(old: Something?, new: Something?): Something = when {
old != null && new != null -> doSomething(old, new) // both smart casted as not nullable
new != null -> doAnotherThing(new) // smart casted as not nullable
old != null -> doAnotherThing(old) // smart casted as not nullable
else -> throw IllegalArgumentException("Both old and new arguments are null")
}
but I’m surprised that the original code doesn’t workSam
04/03/2025, 8:54 AMMatias Reparaz
04/03/2025, 2:42 PMMatias Reparaz
04/03/2025, 2:45 PMChrimaeon
04/03/2025, 6:28 PMfalse
the second one is not going to be evaluated. so in your initial example with the &&
if old == null
the compiler cannot say anything about the value of new
.
example with a basic if expression. https://pl.kotl.in/5M83m7RwWMatias Reparaz
04/03/2025, 6:37 PMVampire
04/03/2025, 7:31 PMnull
and that if the second path is taken only old
is null
as otherwise the first path would have been taken.
But I still think it is just not aware as that needs interpretation skills that are trivial for human but not for the compiler unless explicitly told. 🤷♂️Vampire
04/04/2025, 4:20 PMVampire
04/04/2025, 4:20 PM