September 2019
Intermediate to advanced
462 pages
11h 3m
English
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.
Suppose we have a function that returns a message of different types, like this one:
| | fun fetchMessage(id: Int): Any = |
| | if (id == 1) "Record found" else StringBuilder("data not found") |
Now suppose that we want to receive ...
Read now
Unlock full access