目录
把一个对象成员解构成多个变量,成为解构函数,component1(),component2()等函数是Kotlin约定的操作符。
解构函数可以用于:
data class Person(val name: String, val age: Int)
fun main(args: Array) {
val (name, age) = Person("person", 1)
println(name)
println(age)
}
这样的写法实际上就是避免了以往(对象.属性)调用方式,我们也知道(对象.属性)实际上就是调用了该类的get方法。通过反编译得到的代码为:
public final class HelloKt {
public static final void main(@NotNull String[] args) {
Person person = new Person("person", true);
String str = person.component1();
int age = person.component2();
System.out.println(str);
System.out.println(age);
}
}
data class Person(val name: String, val age: Int)
val list: List = listOf(Person("one", 1),
Person("two", 2),
Person("three", 3),
Person("four", 4))
fun main(args: Array) {
list.forEach { (name, age) ->
println("name:$name, age:$age")
}
}
反编译如下:
public final class HelloKt {
Iterator iterator = $this$forEach$iv.iterator();
if (iterator.hasNext()) {
Object element$iv = iterator.next();
Person $dstr$name$age = (Person)element$iv;
String name = $dstr$name$age.component1();
int age = $dstr$name$age.component2();
String str = "name:" + name + ", age:" + age;
System.out.println(str);
}
}
可以看到$dstr$name$age
该变量存储了一个People临时变量,使用方法类似于Lambda表达式。
fun getPair(after: String?, afterAge: Int?): Pair {
var name = "yangjin"
var age ?: 23
return Pair(name, age)
}
fun main(args: Array) {
val (name, age) = getPair("jowan", null)
println("name:$name, age:$age");
}
反编译的代码如下:
public static final Pair getPair(@Nullable String after, @Nullable Integer afterAge) {
String name = "yangjin";
int age = 23;
name = name;
age = (afterAge != null) ? afterAge.intValue() : age;
return new Pair(name, Integer.valueOf(age)); }
public static final void main(@NotNull String[] args) {
Pair pair = getPair("jowan", null);
String str1 = (String)pair.component1();
int age = ((Number)pair.component2()).intValue();
String str2 = "name:" + str1 + ", age:" + age;
boolean bool = false; System.out.println(str2);
}
}
可以看到,函数的这种实现方式实际上就是用Pair来实现的。Pair存在两个参数,而且其重写了ComponentN的方法。
解构声明还可以Map中,前提条件是:
通过提供一个iterator()函数将每个映射表示为一个值
通过提供函数component1()和component2()来将每个元素呈现为一对
val map: Map = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
fun main(args: Array) {
map.forEach { (name, age) ->
println("name:$name, age:$age")
}
}
反编译的代码如下:
public static final void main(@NotNull String[] args) {
Intrinsics.checkParameterIsNotNull(args, "args");
Map $this$forEach$iv = map;
Map map1 = $this$forEach$iv;
Iterator iterator = map1.entrySet().iterator();
if (iterator.hasNext()) {
Map.Entry element$iv = (Map.Entry)iterator.next(), $dstr$name$age = element$iv;
Map.Entry entry = $dstr$name$age;
String name = (String)entry.getKey();
int age = ((Number)entry.getValue()).intValue();
String str = "name:" + name + ", age:" + age;
System.out.println(str);
}
}