Type Checking and Casting

Sometimes you may wonder if the object at hand is of a particular type you expect. And, once you verify, you often cast the reference to that type so you can invoke the methods you desire—well, at least, that’s the case in Java. Here we’ll see how Kotlin supports these two operations of type checking and type casting. Along the way you’ll see how to benefit from Kotlin’s type safety, and at the same time see how the language removes your need to write mundane code.

Type Checking

“Is it a feature or a flaw?” is an unsettled debate about runtime type checking. It’s necessary to check an object’s type occasionally, but from the extensibility point of view, we should use it sparingly. Checking for arbitrary types can make ...

Get Programming Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.