operator: 将一个函数标记为重载一个操作符或者实现一个约定。
示例:
class User(var age: Int, var name: String) {
//按照参数个数,必须在component后面加上1234
operator fun component1() = age
operator fun component2() = name
}
fun user2(){
val user = User(18, "jack")
//允许将user直接赋值给一个拆解后的对象(age和name)
val (age, name) = user
println("$age $name")
//该解构方法应用于map的遍历比较方便
// val map = mapOf("..key.." to "key","..value.." to "value")
val map2 = mapOf(Pair("key..","value.."))
//map可以直接解构
for ((k,v) in map2){
println("$k $v") //输出:key.. value..
}
//list的话需要用上withIndex,withIndex提供了一个迭代器
val list = arrayListOf("a","b","c","d")
for ((index,str) in list.withIndex()){
println("第$index 个元素是$str")
}
}