Search code examples
androidkotlincompiler-warningskotlin-null-safety

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?


Solution

  • 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.