August 2017
Intermediate to advanced
440 pages
10h
English
Let's represent the Animal and Fish classes from the previous section:

Let's assume we want to call the isHungry method and we want to check if the animal is an instance of Fish. In Java, we would have to do something like this:
//Java
if (animal instanceof Fish){
Fish fish = (Fish) animal;
fish.isHungry();
//or
((Fish) animal).isHungry();
}
The problem with this code is its redundancy. We have to check if the animal instance is Fish and then we have to explicitly cast animal to Fish after this check. Wouldn't it be nice if the compiler could handle this for us? It turns out that the Kotlin compiler is really smart when ...
Read now
Unlock full access