一、解构
Kotlin
中使用operator
关键字修饰函数,这样可以将一个函数标记为重载一个操作符或者实现一个约定。使用operator
关键字修饰函数并且函数名只能为component1
、component2
、component3
…时就是实现一个约定。
通过将该类实例赋值给一组变量,Kotlin
可以直接将对应函数的值按照component1
、component2
、component3
…的顺序赋值给该组变量,这个过程就叫"解构"。
class User(var age: Int, var name: String){
operator fun component1() = age
operator fun component2() = name
}
fun main(args: Array<String>) {
val user = User(11, "Irving")
//将该类实例赋值给一组变量
val (age, name) = user
println(age)
println(name)
}
解构更常用的是在遍历一个map
的时候,通过将map
中的每一对键值对赋值给一组变量(key, value)
,从而可以同时遍历key
和value
。
fun main(args: Array<String>) {
val map = mapOf("key1" to "value1", "key2" to "value2")
for((key, value) in map){
println("$key --> $value")
}
}
二、循环
Kotlin
中的循环有以下几种形式
-
使用
in
关键字,in
关键字后面为一个闭区间,表示从小到大遍历。for (i in