• Scope Functions

      • let

        1. fun customPrint(s: String) {
        2. print(s.uppercase())
        3. }
        4. fun main() {
        5. val empty = "test".let {
        6. customPrint(it)
        7. it.isEmpty()
        8. }
        9. println("$empty")
        10. fun printNonNull(str:String?) {
        11. println("Printing $str")
        12. str?.let {
        13. print("\t")
        14. customPrint(it)
        15. }
        16. }
        17. fun printIfBothNonNull(strOne: String?, strTwo: String?) {
        18. strOne?.let { firstString ->
        19. strTwo?.let { secondString ->
        20. customPrint("$firstString : $secondString")
        21. println()
        22. }
        23. }
        24. }
        25. printNonNull(null)
        26. printNonNull("my string")
        27. printIfBothNonNull("First","Second")
        28. printIfBothNonNull("1",null)
        29. }
      • run,通过this取object

        fun main() {
        fun getNullableLength(ns:String?) {
         println("for \"$ns\":")
         ns?.run {
             println("\tis empty? " + isEmpty())
             println("\tlength = $length")
             length
         }
        }
        getNullableLength(null)
        getNullableLength("")
        getNullableLength("some string with Kotlin")
        }
        
      • with

        class Configuration(var host: String, var port: Int) 
        fun main() {
        val configuration = Configuration(host = "127.0.0.1", port = 9000) 
        
        with(configuration) {
          println("$host:$port")
        }
        // instead of:
        println("${configuration.host}:${configuration.port}")    
        }
        
      • apply,自动返回调用对象本身

        data class Person(var name: String, var age:Int, var about:String) {
        constructor():this("",0,"")
        }
        fun main() {
        val jake = Person()
        val stringDescription = jake.apply {
           name = "Jake"
           age = 30
           about = "Android developer"
        }.toString()
        println(stringDescription)
        }
        
      • also,也是执行代码块后返回对象,通过it进行引用,主要用于额外的操作

        data class Person(var name: String, var age: Int, var about: String) {
               constructor() : this("", 0, "")
        }
        fun writeCreationLog(p: Person) {
        println("A new person ${p.name} was created.")
        }         
        fun main() {
        val jake = Person("Jake",30,"Android developer")
          .also {
              writeCreationLog(it)
          }
        }
        
    • 代理

      interface SoundBehavior {
        fun makeSound()
      }
      class ScreamBehavior(val n:String): SoundBehavior {
        override fun makeSound() = println("${n.toUpperCase()} !!!")
      }
      class RockAndRollBehavior(val n:String): SoundBehavior {
        override fun makeSound() = println("I'm The King of Rock 'N' Roll: $n")
      }
      class TomAraya(n:String): SoundBehavior by ScreamBehavior(n)
      class ElvisPresley(n:String): SoundBehavior by ScreamBehavior(n)
      fun main() {
        val tomAraya = TomAraya("Thrash Metal")
        tomAraya.makeSound()
        val elvisPresley = ElvisPresley("Dancin to the Jailhouse Rock")
        elvisPresley.makeSound()
      }
      

      ```kotlin //代理属性 class Example { var p:String by Delegate() override fun toString() = “Example Class” } class Delegate() { operator fun getValue(thisRef: Any?, prop: KProperty<*>): String {

       return "$thisRef, thank you for delegating '${prop.name}' to me!"
      

      } operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: String) {

       println("$value has been assigned to ${prop.name} in $thisRef")
      

      } } fun main() { val e = Example() println(e.p) e.p = “NEW” } //Standard Delegates class LazySample { init { println(“created!”) } val lazyStr: String by lazy { println(“computed!”) “my lazy” } }

    fun main() { val sample = LazySample() println(“lazyStr = ${sample.lazyStr}”)//需要计算缓存结果 println(“ = ${sample.lazyStr}”)//直接取结果 }

    
    -  解构
    ```kotlin
    fun findMinMax(list: List<Int>): Pair<Int,Int> {
        //do the math
        return Pair(50, 100)
    }
    fun main() {
        val (x,y,z) = listOf(2,34,4)
        val map = mapOf("Alice" to 21, "Bob" to 25)
        for((name, age) in map) {
            println("$name is $age years old")
        }
        val (min,max) = findMinMax(listOf(100,90,60))
    }
    
    data class User(val username:String, val email:String)
    fun getUser() = User("Mary", "mary@somewhere.com")
    fun main() {
        val user = getUser()
        val (username, email) = user
        println(username == user.component1())
        val (_, emailAddress) = getUser()
    }
    
    class Pair<K, V>(val first: K, val second: V) {
        operator fun compenent1(): K {
            return first
        }
        operator fun component2(): V {
            return second
        }
    }
    
    fun main() {
        val (num, name) = Pair(1,"one")
        println("num = $num, name = $name")
    }