Hey guys! While reviewing PR I've spotted a smell...
# announcements
k
Hey guys! While reviewing PR I've spotted a smelly code.
Copy code
fun x(anInt: Int) : String {
    when (anInt) {
        0 -> return "zero"
        1 -> return "one"
    }
    return null!!
}
Despite the 'quality` of code itself I'm curious why compiler thinks that
return null!!
is fine (IDE hints that return statement is unreachable which is false)? And similarly why this
val a : Int = null!!
is allowed as well.
g
Because it is as fine as
throw Exception()
👍 1
the return is unreachable, as the exception will be thrown before returning
👍 1
m
null!!
has type
Nothing
, which is a subclass of every type. You can therefore return it from everything (for the same reason you can throw exceptions). The
return
is unreachable because there is an expression of type
Nothing
before it.
👍 1
k
Cool beans, checked with decompiled code and make sense.
k
The type of
null
is `Nothing?`:
m
Yes, therefore the type of
null!!
becomes
Nothing
.
p
I'd move the return out of the when block and use an
else -> error("Invalid anInt=$anInt")