Why do unsafe .run() call works fine on a null value in Kotlin?

Viewed 1647

I have the following code fragment:

val foo: String? = null
foo.run { println("foo") }

I have here a nullable variable foo that is actually set to null followed by a nonsafe .run() call.

When I run the code snippet, I get foo printed out despite the fact that the run method is called on a null. Why is that? Why no NullPointerException? Why does compiler allow a nonsafe call on an optional value?

If I pass println(foo), I get a nice juicy null in the console so I think it's safe to assume that foo is actually null.

3 Answers
Related