Scope Functions
let
fun customPrint(s: String) {print(s.uppercase())}fun main() {val empty = "test".let {customPrint(it)it.isEmpty()}println("$empty")fun printNonNull(str:String?) {println("Printing $str")str?.let {print("\t")customPrint(it)}}fun printIfBothNonNull(strOne: String?, strTwo: String?) {strOne?.let { firstString ->strTwo?.let { secondString ->customPrint("$firstString : $secondString")println()}}}printNonNull(null)printNonNull("my string")printIfBothNonNull("First","Second")printIfBothNonNull("1",null)}
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")
}
