Option 与空安全

Scoop 在运行期没有 null。“可能没有值”由核心库的普通 enum Option<T> 表示,T? 只是它的简写。Kotlin 的空安全运算符照常可用,但它们是对 Option 的模式匹配,而不是空指针检查。

定义

public enum Option<T> {
    Some(T),
    None
}
  • T? 在编译期展开为 Option<T>,二者完全等价。
  • 展开是逐层的:T?? 是 Option<Option<T>>,Some(None) 与 None 是不同的值。这与 Kotlin(T?? 等于 T?)不同。
  • Some 与 None 默认可见,不需要写 Option. 前缀。
  • 构造可选值必须显式写 Some(x) 或 None:val s: String? = "a" 是编译错误,应写 Some("a")。
  • Option 与所有泛型一样是不变的:Option<Circle> 不是 Option<Shape>,需要转换时用 map 或重新构造。
  • 引用类型、Ptr 与 FunPtr 的 Option 不占用额外空间,None 用全零表示。

空安全运算符

表达式等价写法结果类型
a?.bwhen (a) { case Some(val v) -> Some(v.b); case None -> None }B?
a?.f(args)when (a) { case Some(val v) -> Some(v.f(args)); case None -> None }R?
a ?: bwhen (a) { case Some(val v) -> v; case None -> b }T 与 b 的共同类型
a!!Some(v) 时为 v,None 时抛出 UnwrapExceptionT
e as? T转换成功为 Some(值),失败为 NoneT?
struct User(val name: String, val email: String?)

fun find(id: Int): User? = if (id == 1) Some(User("Ada", Some("[email protected]"))) else None

fun main() {
    val name = find(2)?.name ?: "nobody"
    println(name)                              // nobody
    val email: String?? = find(1)?.email       // 安全调用不展平:Option<Option<String>>
    println(email == Some(Some("[email protected]")))
    println(find(1)!!.name)                    // Ada
    val any: Any = "text"
    println(any as? String ?: "not a string")  // text
}

安全调用

  • 接收者 a 只求值一次。只有在 a 为 Some 时才会求值实参、计算默认参数并调用函数;为 None 时这些都不发生。
  • 结果不展平:若 f 返回 R?,a?.f() 的类型是 R??;若返回 Unit,结果是 Unit?。链式访问因此需要在每一层处理嵌套,例如先用 ?: 合并:(u?.email ?: None)?.charLength。
  • 安全调用可以作为丢弃结果的语句,例如 resource?.close()。
  • 不支持通过安全调用赋值:a?.b = c 是编译错误。
fun expensive(): Int {
    println("evaluated")
    return 1
}

fun main() {
    val n: Int? = None
    val result = n?.plus(expensive())   // n 为 None:expensive() 不会被调用
    println(result == None)
}

Elvis 运算符

a ?: b 先求值 a,只在 None 时求值 b。右侧可以是 return、throw 或其他 Nothing 表达式,此时整个表达式的类型就是载荷类型 T。Elvis 是右结合的:a ?: b ?: c 等于 a ?: (b ?: c)。

fun describe(value: Int?): String {
    val number = value ?: return "missing"
    return f"number ${number}"
}

fun require(value: String?): String = value ?: throw IllegalArgumentException(Some("value required"))

fun main() {
    println(describe(None))
    println(describe(Some(3)))
    println(require(Some("ok")))
}

Elvis 的优先级低于算术、区间和 infix 调用,高于比较与相等:a ?: 1 + 2 等于 a ?: (1 + 2),count ?: 0 > 0 等于 (count ?: 0) > 0。完整优先级见运算符优先级。

取出载荷

Option 没有判空后的 smart cast:判断 x != None 之后,x 的类型仍是 T?。取出载荷有以下几种方式:

  • when 模式,可以嵌套匹配载荷的结构;
  • ?: 提供缺省值或提前返回;
  • !! 在确信有值时强制取出;
  • 标准库 scoop.std 中的扩展函数 map、flatMap、filter、fold、getOrElse、orElse 等(需要 import scoop.*)。
import scoop.*

struct User(val name: String, val email: String?)

fun contact(user: User?): String = when (user) {
    case Some(User { email: Some(val address), .. }) -> address
    case Some(User { val name, .. }) -> f"${name} (no email)"
    case None -> "unknown"
}

fun main() {
    println(contact(Some(User("Ada", Some("[email protected]")))))
    println(contact(Some(User("Lin", None))))
    println(contact(None))
    val doubled = Some(21).map { it * 2 }
    println(doubled.getOrElse { 0 })
}
fun main() {
    val x: Int? = Some(1)
    if (x != None) {
        println(x + 1)     // 编译错误:x 仍是 Option<Int>,没有 plus
    }
}

嵌套 Option

因为可空不合并,Option 可以精确表达“查到了一个空值”与“没查到”的区别。例如映射表中值类型本身是 V? 时,查询结果 V?? 的 Some(None) 表示键存在但值为空,None 表示键不存在:

fun lookup(key: String): Int?? = when (key) {
    "present" -> Some(Some(1))
    "empty" -> Some(None)
    else -> None
}

fun main() {
    for (key in ["present", "empty", "missing"]) {
        val text = when (lookup(key)) {
            case Some(Some(val v)) -> f"value ${v}"
            case Some(None) -> "explicitly empty"
            case None -> "no such key"
        }
        println(text)
    }
}

在集合中使用

None 是合法的元素值:ArrayList<Int?> 中的 None 只表示该位置的值为空,不表示位置不存在。可选值作为结构的字段时,序列化等库按声明处是否为 Option 决定字段能否省略,见编解码。