Type Checking and Casting
We'll cover the following...
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 the code brittle when new types are added and lead to failure of the Open-Closed Principle—see
Having said that, checking for runtime type is useful and unavoidable in two situations. One is in the implementation of the equals()
method—we need to know if the instance at hand is of the current class. The other is within when
, if the path to take depends on the type of an instance.
Let’s first look at how to check for the runtime type, and then at a nice little feature that removes the burden of casting once the type is confirmed.
Using is
The equals()
method of Object performs reference-based comparison, but classes may override that method to determine equality. Continuing that tradition, all Kotlin classes, which extend from ...