官术网_书友最值得收藏!

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", "ag@t.pl", 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;
}
}
主站蜘蛛池模板: 宾阳县| 亚东县| 赣州市| 乌拉特中旗| 芷江| 柯坪县| 明水县| 鄂州市| 云阳县| 桃园县| 尼木县| 新和县| 道孚县| 花垣县| 邵东县| 临桂县| 松江区| 沁水县| 元江| 平昌县| 桐柏县| 长垣县| 临安市| 沁源县| 靖安县| 富川| 岳池县| 德庆县| 石景山区| 兴城市| 贵州省| 故城县| 焉耆| 汝州市| 龙南县| 阜阳市| 新宾| 沁水县| 武汉市| 汉源县| 莱西市|