Kotlin Notes - 6

发布时间 2023-12-04 23:08:58作者: Otlpy
  1. To access this from an outer scope (a class, extension function, or labeled function literal with receiver) you write this@label, where @label is a label on the scope this is meant to be from:

    class A { // implicit label @A
        inner class B { // implicit label @B
            fun Int.foo() { // implicit label @foo
                val a = this@A // A's this
                val b = this@B // B's this
    
                val c = this // foo()'s receiver, an Int
                val c1 = this@foo // foo()'s receiver, an Int
    
                val funLit = lambda@ fun String.() {
                    val d = this // funLit's receiver, a String
                }
    
                val funLit2 = { s: String ->
                    // foo()'s receiver, since enclosing lambda expression
                    // doesn't have any receiver
                    val d1 = this
                }
            }
        }
    }
    
  2. Destructuring declarations

    val (name, age) = person
    
    for ((a, b) in collection) { ... }
    
    for ((key, value) in map) {
       // do something with the key and the value
    }
    
    val (_, status) = getResult()
    
    map.mapValues { entry -> "${entry.value}!" }
    map.mapValues { (key, value) -> "$value!" }