Malwinder Singh
Malwinder Singh

Reputation: 7070

Smart cast to kotlin.String

I was trying Kotlin and got message from compiler:

Smart cast to kotlin.String

Code:

/*"mTripStatus" is a nullable String*/
var html :String = HTML
html = if (mTripStatus!=null) html.replace("TRIP_STATUS_VALUE", mTripStatus) else html

What does this mean?

Upvotes: 8

Views: 6022

Answers (2)

Hector Da SIlva
Hector Da SIlva

Reputation: 21

This code:

var html :String = HTML
html = if (mTripStatus!=null) html.replace("TRIP_STATUS_VALUE", mTripStatus) else html

can be:

var html: String = html
mTripStatus?.let { html = html.replace("TRIP_STATUS_VALUE", mTripStatus) }

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272667

The compiler knows that mTripStatus cannot be null if the if condition is satisfied, so it performs a smart cast from String? to String. That's what allows html.replace("TRIP_STATUS_VALUE", mTripStatus) to compile.

But note that this shouldn't be interpreted as a compiler warning. This is idiomatic Kotlin code.

Upvotes: 13

Related Questions