interface Uri {
val fragment: String?
}
class Path : Uri {
override val fragment: Nothing? = null
}
fun main() {
val p: Path = Path()
val x: String? = p.fragment?.substring(0, 1)
println(x)
}
I would have hoped the covariant return type of
Nothing?
would have meant the compiler stopped me using
fragment
as a
String?
given
p
is typed as a
Path
.
s
Sam
08/09/2023, 2:28 PM
Actually it works because
substring
is an extension function.
Nothing
can substitute for any type, so you can actually always call any extension function of any type on a value of type
Nothing
. The fact that your
fragment
overrides a property of type
String
doesn’t make a difference one way or the other. This also compiles:
Copy code
fun main() {
val n: Nothing? = null
println(n?.substring(0, 1))
}
r
Rob Elliot
08/09/2023, 2:28 PM
Ah, thanks! Missed it was an extension function.
s
Sam
08/09/2023, 2:28 PM
Fun fact: IntelliJ deliberately avoids doing autocompletion for extensions on
Nothing
, otherwise it would end up suggesting every extension function in the world