Let's say I have a simple class Foo
with a nullable String?
data class Foo(
val bar: String?
)
and I create a simple function capitalize
fun captitalize(foo: Foo) = when {
foo.bar != null -> runCatching { foo.bar.capitalize() }
else -> ""
}
which works fine, because the compiler infers that foo.bar cannot be null eventhough it's type is nullable. But then I decide to write the same function as an extension of Foo
fun Foo.captitalize2() = when {
bar != null -> runCatching { bar.capitalize() }
else -> ""
}
and all of a sudden the compiler is no longer able to infer that bar is not null, and IntelliJ tells me that "only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable reciever of type String?"
Can anyone explain why?
runCatching
invocation incapitalize2
is an invocation ofpublic inline fun <T, R>
T.runCatching(block: T.() -> R) : Result<R>` and type parameters are inferred asrunCatching<Foo, String>
:T
isFoo
for the compiler, notFoo having not null property bar
, so you obtain the compilation error... When you inline the function there is no type inference betweenwhen
andbar.capitalize()
, so the compiler is happy and you have no errors... – Rancell