Destructuring types

It is often practical to convert a single object of a complex type into a number of variables. This allows you to provide proper naming for the variables and simplifies the code. Kotlin provides an easy, built-in way to achieve this with a feature called destructuring:

data class User(val login: String, val email: String, val birthday: LocalDate)

fun getUser() = User("Agata", "[email protected]", LocalDate.of(1990, 1, 18))

val (name, mail, birthday) = getUser()

print("$name was born on $birthday")

As a result, this piece of code would print the following message to the console:

Agata was born on 1990-01-18

Pretty awesome! Destructuring is available for data classes out of the box. The Kotlin standard library provides this feature for many common types as well. However, destructuring is not available explicitly whenever we are dealing with custom, non-data classes. Especially, while working with classes from external libraries written in other languages such as Java, we need to define the destructuring mechanism manually. In this recipe, we are going to implement destructuring for a Java class defined as follows:

// Java code
public class
LightBulb {
private final int id;
private boolean turnedOn = false;

public LightBulb(int id) {
this.id = id;
}

public void setTurnedOn(boolean turnedOn) {
this.turnedOn = turnedOn;
}

public boolean getTurnedOn() {
return turnedOn;
}

public int getId() {
return id;
}
}
..................Content has been hidden....................

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