I was surprised this compiled: ```interface Uri { ...
# getting-started
r
I was surprised this compiled:
Copy code
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
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
Ah, thanks! Missed it was an extension function.
s
Fun fact: IntelliJ deliberately avoids doing autocompletion for extensions on
Nothing
, otherwise it would end up suggesting every extension function in the world
💡 3
😄
r
Nice!