lyt 发布的文章

// All examples create a function object that performs upper-casing.
// So it's a function from String to String

val upperCase1: (String) -> String = { str: String -> str.toUpperCase() } // 1

val upperCase2: (String) -> String = { str -> str.toUpperCase() }         // 2

val upperCase3 = { str: String -> str.toUpperCase() }                     // 3

// val upperCase4 = { str -> str.toUpperCase() }                          // 4

val upperCase5: (String) -> String = { it.toUpperCase() }                 // 5

val upperCase6: (String) -> String = String::toUpperCase                  // 6

println(upperCase1("hello"))
println(upperCase2("hello"))
println(upperCase3("hello"))
println(upperCase5("hello"))
println(upperCase6("hello"))

fun main() {

test("fd1",1,2)
test("fd2")

// 注意这里,要调用 toIntArray,如果直接传*arg是有类型错误
val arg = arrayOf(3,4)
test("fd3", *arg.toIntArray())

}

fun test(name:String,vararg args:Int){

println("$name size ${args.size}")
print(name)
for(it in args){
    print(" ")
    print(it)
}
print("\n")

}

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

}