Pattern matching

The concept of pattern matching is like switch/case on steroids for someone who comes from Java. We've already seen how when expression can be used, in Chapter 1, Getting Started with Kotlinso let's briefly discuss why this concept is important for the functional paradigm.

As you may know, switch in Java accepts only some primitive types, strings, or enums.

Consider the following code in Java:

class Cat implements Animal {
public String purr() {
return "Purr-purr";
}
}

class Dog implements Animal {
public String bark() {
return "Bark-bark";
}
}

interface Animal {}

If we were to decide which of the functions to call, we would need something like this:

public String getSound(Animal animal) {
String sound = null;
if (animal instanceof Cat) {
sound = ((Cat)animal).purr();
}
else if (animal instanceof Dog) {
sound = ((Dog)animal).bark();
}

if (sound == null) {
throw new RuntimeException();
}
return sound;
}

This method could be shortened by introducing multiple returns, but in real projects, multiple returns are usually bad practice. 

Since we don't have a switch statement for classes, we need to use an if statement instead. 

Compare that with the following Kotlin code:

fun getSound(animal: Animal) = when(animal) {
is Cat -> animal.purr()
is Dog -> animal.bark()
else -> throw RuntimeException()
}

Since when is an expression, we avoided the intermediate variable altogether. But what's more, using pattern matching, we can also avoid most of the code that concerns type checks and casts.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.70.101