2021年7月

这里Mammal 类外部就是不可见的

sealed class Mammal(val name: String)                                                   // 1

class Cat(val catName: String) : Mammal(catName)                                        // 2
class Human(val humanName: String, val job: String) : Mammal(humanName)

fun greetMammal(mammal: Mammal): String {
    when (mammal) {                                                                     // 3
        is Human -> return "Hello ${mammal.name}; You're working as a ${mammal.job}"    // 4
        is Cat -> return "Hello ${mammal.name}"                                         // 5     
    }                                                                                   // 6
}

fun main() {
    println(greetMammal(Human("fd", "IT")))
    println(greetMammal(Cat("Snowy")))
}

常用方法:

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")
    }
}