Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 879
Malwinder Singh Avatar asked Dec 04 '17 19:12

Malwinder Singh


People also ask

Is smart cast in Kotlin?

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.

How do you do type checking in Kotlin?

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.


1 Answers

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.

like image 121
Oliver Charlesworth Avatar answered Sep 26 '22 06:09

Oliver Charlesworth