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?
Smart cast is a feature in which the Kotlin compiler tracks conditions inside of an expression. If the compiler finds a variable that is not null of type nullable then the compiler will allow to access the variable.
In Java, we can use the instanceof operator to check the type of a given object. For example, we can use “instanceof String” to test if an object is of the type String: Object obj = "I am a string"; if (obj instanceof String) { ... } In Kotlin, we use the 'is' operator to check if the given object is in a certain type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With