Explicit Type Casting

We'll cover the following...

When to use explicit casting

Use explicit casts only in situations where smart casts aren’t possible—that is, when the compiler can’t determine the type with confidence. For example, if a var variable were to change between the check and its use, then Kotlin can’t guarantee the type. In such cases it won’t apply smart casts, and we have to take the responsibility for casts.

Kotlin provides two operators to perform explicit cast: as and as?. Let’s create an example that illustrates how to use both of them.

Using as

Suppose we have a function that returns a message of different types, like this one:

// unsafecast.kts
fun fetchMessage(id: Int): Any =
  if (id == 1) "Record found" else StringBuilder("data not found")

Now suppose that we want to receive the message by calling the above function, and print some details about ...