google kotlin 训练营-扩展

2020-07-22  本文已影响0人  wwq2020

原文

pair

两个值,通过 to 链接

val equipment = "fish net" to "catching fish"
println("${equipment.first} used for ${equipment.second}")

tripple

通过.first, .second and .third 代表各个值

val numbers = Triple(6, 9, 42)
println(numbers.toString())
println(numbers.toList())

pair 和 tripple 可以嵌套

val equipment2 = ("fish net" to "catching fish") to "equipment"

pair,tripple 解构

val equipment = "fish net" to "catching fish"
val (tool, use) = equipment
println("$tool is used for $use")
val numbers = Triple(6, 9, 42)
val (n1, n2, n3) = numbers
println("$n1 $n2 $n3")

集合

列表

val list2 = listOf("a", "bbb", "cc")
for (s in list2.listIterator()) {
    println("$s ")
}

map

// 默认不可变
val cures = hashMapOf("white spots" to "Ich", "red sores" to "hole disease")
println(cures.get("white spots"))
// 取不到时取默认值
println(cures.getOrDefault("bloating", "sorry, I don't know"))
// 取不到时取执行
println(cures.getOrElse("bloating") {"No cure for this"})

// 可变
val inventory = mutableMapOf("fish net" to 1)
inventory.put("tank scrubber", 3)
println(inventory.toString())
inventory.remove("fish net")
println(inventory.toString())

const

const val 定义的变量不可变

const val rocks = 3

const val 定义的变量在编译器
val 定义的变量在运行时

val value1 = complexFunctionCall() // OK
const val CONSTANT1 = complexFunctionCall() // NOT ok

In addition, const val only works at the top level, and in singleton classes declared with object, not with regular classes. You can use this to create a file or singleton object that contains only constants, and import them as needed.

定义 const val

方式一

object Constants {
const val CONSTANT2 = "object constant"
}
val foo = Constants.CONSTANT2

方式二

class MyClass {
companion object {
const val CONSTANT3 = "constant in companion"
}
}

写扩展方法

fun String.hasSpaces(): Boolean {
    val found = this.find { it == ' ' }
    return found != null
}
println("Does it have spaces?".hasSpaces())

扩展方法只能访问类的 public API,private 不能访问

扩展属性

val AquariumPlant.isGreen: Boolean
   get() = color == "green"

可空的接收者

fun AquariumPlant?.pull() {
   this?.apply {
       println("removing $this")
   }
}

val plant: AquariumPlant? = null
plant.pull()
上一篇下一篇

猜你喜欢

热点阅读