Does a.run same as a?.run in kotlin

80 views Asked by At

If a variable is nullable in Kotlin, we need to either do a safety call ?., or !!. for explicitly call.

When I was trying to use some extensions(such as run or let) from nullable variable , I noticed that .run is fine and IDE did not complain it, usually I will receive a warning to remind me it is not a safety call.

Does it make any difference for ?.run{} and .run{} in kotlin? Is it considered as null safety if I use .run{} ?

var a? = "..."

a?.run{}

a.run{}
1

There are 1 answers

0
Todd On BEST ANSWER

You'll need to safely handle the null somewhere.

Either when accessing a:

a?.run { } 

Or when accessing this inside run on a:

a.run { this?.toSomething() }

Using a String? as an example, these both print null and the compiler is ok with both:

val x: String? = null
println(x.run { this?.toUpperCase() }) // prints null, type is String?
println(x?.run { this.toUpperCase() }) // prints null, type is String?