Rob Elliot
08/09/2023, 2:21 PMinterface 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.Sam
08/09/2023, 2:28 PMsubstring 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:
fun main() {
val n: Nothing? = null
println(n?.substring(0, 1))
}Rob Elliot
08/09/2023, 2:28 PMSam
08/09/2023, 2:28 PMNothing, otherwise it would end up suggesting every extension function in the worldSam
08/09/2023, 2:28 PMRob Elliot
08/09/2023, 2:29 PM