Kotlin学习笔记:习惯用法

作者: 小村医 | 来源:发表于2019-07-13 16:03 被阅读5次

使用可空值及 null 检测

当某个变量的值可以为 null 的时候,必须在声明处的类型后添加 ? 来标识该引用可为空。
如果 str 的内容不是数字返回 null:

fun parseInt(str: String): Int? {
    // ……
}

使用类型检测及自动类型转换

is 运算符检测一个表达式是否某类型的一个实例。

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // `obj` 在该条件分支内自动转换成 `String`
        return obj.length
    }

    // 在离开类型检测分支后,`obj` 仍然是 `Any` 类型
    return null
}

使用 when 表达式

fun describe(obj: Any): String =
    when (obj) {
        1          -> "One"
        "Hello"    -> "Greeting"
        is Long    -> "Long"
        !is String -> "Not a string"
        else       -> "Unknown"
    }

使用区间(range)

使用 in 运算符来检测某个数字是否在指定区间内:

val x = 10
val y = 9
if (x in 1..y+1) {
    println("fits in range")
}

使用 lambda 表达式来过滤(filter)与映射(map)集合

val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
  .filter { it.startsWith("a") }
  .sortedBy { it }
  .map { it.toUpperCase() }
  .forEach { println(it) }

函数的默认参数

fun foo(a: Int = 0, b: String = "") { …… }

只读 list

val list = listOf("a", "b", "c")

只读 map

val map = mapOf("a" to 1, "b" to 2, "c" to 3)

延迟属性

val p: String by lazy {
    // 计算该字符串
}

扩展函数

fun String.spaceToCamelCase() { …… }
"Convert this to camelcase".spaceToCamelCase()

创建单例

object Resource {
    val name = "Name"
}

If not null 缩写

val files = File("Test").listFiles()

println(files?.size)

If not null and else 缩写

val files = File("Test").listFiles()
println(files?.size ?: "empty")

if null 执行一个语句

val values = ……
val email = values["email"] ?: throw IllegalStateException("Email is missing!")

if not null 执行代码

val value = ……

value?.let {
    …… // 代码会执行到此处, 假如data不为null
}

映射可空值(如果非空的话)

val value = ……
val defaultValueIfValueIsNull = ……

val mapped = value?.let { transformValue(it) } ?: defaultValueIfValueIsNull

“try/catch”表达式

fun test() {
    val result = try {
        count()
    } catch (e: ArithmeticException) {
        throw IllegalStateException(e)
    }

    // 使用 result
}

单表达式函数

fun theAnswer() = 42

等价于

fun theAnswer(): Int {
    return 42
}

run

用法1

函数定义:

public inline fun <R> run(block: () -> R): R = block()

功能:调用run函数块。返回值为函数块最后一行,或者指定return表达式。
示例:

val a = run {
    println("run")
    return@run 3
}
println(a)

运行结果:
run
3

用法2

函数定义:

public inline fun <T, R> T.run(block: T.() -> R): R = block()

功能:调用某对象的run函数,在函数块内可以通过 this 指代该对象。返回值为函数块的最后一行或指定return表达式。
示例:

val a = "string".run {
    println(this)
    3
}
println(a)

运行结果:
string
3

apply

函数定义:

public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }

功能:调用某对象的apply函数,在函数块内可以通过 this 指代该对象。返回值为该对象自己。
示例:

val a = "string".apply {
    println(this)
}
println(a)

运行结果:
string
string

let

函数定义:

public inline fun <T, R> T.let(block: (T) -> R): R = block(this)

功能:调用某对象的let函数,则该对象为函数的参数。在函数块内可以通过 it 指代该对象。返回值为函数块的最后一行或指定return表达式。
示例:

val a = "string".let {
    println(it)
    3
}
println(a)

运行结果:
string
3

also

函数定义(Kotlin1.1新增的):

public inline fun <T> T.also(block: (T) -> Unit): T { block(this); return this }

功能:调用某对象的also函数,则该对象为函数的参数。在函数块内可以通过 it 指代该对象。返回值为该对象自己。
示例:

val a = "string".also {
    println(it)
}
println(a)

运行结果:
string
string

with

函数定义:

public inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()

功能:with函数和前面的几个函数使用方式略有不同,因为它不是以扩展的形式存在的。它是将某对象作为函数的参数,在函数块内可以通过 this 指代该对象。返回值为函数块的最后一行或指定return表达式。
示例:

val a = with("string") {
    println(this)
    3
}
println(a)

运行结果:
string
3

相关文章

网友评论

    本文标题:Kotlin学习笔记:习惯用法

    本文链接:https://www.haomeiwen.com/subject/brizhctx.html