分类 Kotlin 下的文章

常用方法:

fun main() {
    for(i in 0..3) {             // 0123 从0到3
        print(i)
    }
    print(" ")

    for(i in 0 until 3) {        // 012 从0到2(不包3)
        print(i)
    }
    print(" ")

    for(i in 2..8 step 2) {      // 2468 步进是2 
        print(i)
    }
    print(" ")

    for (i in 3 downTo 0) {      // 3210 倒数
        print(i)
    }
    print(" ")

}

一些另类用法:

for (c in 'a'..'d') {        // 1
    print(c)
}
print(" ")

for (c in 'z' downTo 's' step 2) { // 2
    print(c)
}
print(" ")

还可以用在if 判断上

val x = 2
if (x in 1..5) {            // 1
    print("x is in range from 1 to 5")
}
println()

if (x !in 6..10) {          // 2
    print("x is not in range from 6 to 10")
}

如果我们想用for in 去遍历一个类。可参重构他的iterator 方法

class Animal(val name: String)

class Zoo(val animals: List<Animal>) {

    operator fun iterator(): Iterator<Animal> {             // 1
        return animals.iterator()                           // 2
    }
}

fun main() {

    val zoo = Zoo(listOf(Animal("zebra"), Animal("lion")))

    for (animal in zoo) {                                   // 3
        println("Watch out, it's a ${animal.name}")
    }

}

所有功能跟also都一样。唯一不同的就是域内使用this调用

fun main(args : Array<String>){
    var v1 = V()
    v1.apply{
        this.name = "fd"
    }.t1("hi")
}

class V {
    var name = "fd"
    
    fun t1(v:String){
        println("test1 $v $name")
    }
}

also就是*.let ,只不过。这域的返回值是also对象本身。不再是最后一行

fun main(args : Array<String>){
    var v1 = V()
    v1.also{
        it.name = "fd"
    }.t1("hi")
}

class V {
    var name = "fd"
    
    fun t1(v:String){
        println("test1 $v $name")
    }
}

let就跟*.run一样。必须有对象,并且这对象会带进匿名函数里,名字叫it

fun main(args : Array<String>){
    var v1 = "fd"
    var v2:String?
    
    v2 = v1?.let{
        it + " hi"
    }
    
    println(v2)
}