2-2-19 快速掌握Kotlin-可空类型扩展函数

在 Kotlin 中,可空类型扩展函数 是一种强大的特性,允许你为可空类型(T?)定义扩展函数。这些函数可以在可空变量上安全调用,避免了显式的空检查。

1. 基本语法

kotlin 复制代码
// 为可空类型 String? 定义扩展函数
fun String?.safeLength(): Int {
    return this?.length ?: 0  // 使用安全调用和 Elvis 操作符
}

fun main() {
    val name: String? = "Kotlin"
    val nullName: String? = null
    
    println(name.safeLength())     // 6
    println(nullName.safeLength()) // 0 - 不会抛出 NPE
}

2. 与不可空扩展函数的区别

kotlin 复制代码
// 不可空扩展函数
fun String.uppercaseFirst(): String {
    return if (this.isNotEmpty()) {
        this[0].uppercase() + this.substring(1)
    } else {
        this
    }
}

// 可空扩展函数
fun String?.safeUppercaseFirst(): String {
    return if (!this.isNullOrEmpty()) {
        this[0].uppercase() + this.substring(1)
    } else {
        this ?: ""  // 处理 null 情况
    }
}

fun main() {
    val str: String? = "hello"
    
    // str.uppercaseFirst()  // 编译错误:需要不可空类型
    println(str.safeUppercaseFirst())  // "Hello"
    
    println(null.safeUppercaseFirst()) // "" - 不会崩溃
}

3. 实际应用示例

示例1:可空集合处理

kotlin 复制代码
fun <T> Collection<T>?.isNullOrEmpty(): Boolean {
    return this == null || this.isEmpty()
}

fun <T> Collection<T>?.safeSize(): Int {
    return this?.size ?: 0
}

fun main() {
    val list: List<String>? = null
    println(list.isNullOrEmpty())  // true
    println(list.safeSize())       // 0
}

示例2:链式调用

kotlin 复制代码
fun String?.toIntOrNull(): Int? {
    return try {
        this?.toInt()
    } catch (e: NumberFormatException) {
        null
    }
}

fun String?.toIntWithDefault(default: Int = 0): Int {
    return this.toIntOrNull() ?: default
}

fun main() {
    val input1: String? = "123"
    val input2: String? = "abc"
    val input3: String? = null
    
    println(input1.toIntWithDefault())  // 123
    println(input2.toIntWithDefault())  // 0
    println(input3.toIntWithDefault())  // 0
}

示例3:DSL 风格扩展

kotlin 复制代码
fun <T> T?.whenNotNull(block: (T) -> Unit) {
    if (this != null) {
        block(this)
    }
}

fun <T, R> T?.whenNotNull(block: (T) -> R, default: R): R {
    return if (this != null) {
        block(this)
    } else {
        default
    }
}

fun main() {
    val name: String? = "Alice"
    val nullName: String? = null
    
    name.whenNotNull {
        println("Name is $it")  // 输出: Name is Alice
    }
    
    nullName.whenNotNull {
        println("This won't print")
    }
    
    val length = name.whenNotNull({ it.length }, 0)
    println(length)  // 5
}

4. 作用域函数扩展

kotlin 复制代码
fun <T : Any> T?.withNotNull(block: T.() -> Unit) {
    this?.block()
}

fun <T : Any, R> T?.letNotNull(block: (T) -> R): R? {
    return this?.let(block)
}

fun <T : Any> T?.alsoNotNull(block: (T) -> Unit): T? {
    this?.also(block)
    return this
}

fun main() {
    val nullableValue: String? = "test"
    
    nullableValue.withNotNull {
        println(uppercase())  // 输出: TEST
    }
    
    val result = nullableValue.letNotNull {
        it.length * 2
    }
    println(result)  // 8
}

5. 实用工具函数

kotlin 复制代码
// 文件路径处理
fun String?.toSafePath(): String {
    return this?.trim()?.removeSuffix("/") ?: ""
}

// 日期字符串解析
fun String?.toDateOrNull(): LocalDate? {
    return try {
        this?.let { LocalDate.parse(it) }
    } catch (e: Exception) {
        null
    }
}

// 数字格式化
fun Number?.formatWithDefault(
    pattern: String = "#,##0.00",
    default: String = "N/A"
): String {
    return try {
        DecimalFormat(pattern).format(this ?: return default)
    } catch (e: Exception) {
        default
    }
}

fun main() {
    val number: Double? = 1234.567
    println(number.formatWithDefault())  // 1,234.57
    println(null.formatWithDefault())    // N/A
}

6. 最佳实践

✅ 推荐的做法:

kotlin 复制代码
// 1. 提供合理的默认值
fun String?.orEmpty(): String = this ?: ""

// 2. 明确表达意图
fun String?.isNotNullOrBlank(): Boolean {
    return !this.isNullOrBlank()
}

// 3. 支持链式调用
fun String?.trimOrNull(): String? {
    return this?.trim()?.takeIf { it.isNotEmpty() }
}

❌ 避免的做法:

kotlin 复制代码
// 避免在扩展函数中抛出异常
fun String?.unsafeLength(): Int {
    return this!!.length  // 不要这样做!
}

// 避免混淆可空和不可空扩展
fun String.unsafeForNullable(): String {
    return this  // 这个函数不能在 null 上调用
}

7. 性能考虑

kotlin 复制代码
// 内联扩展函数减少开销
inline fun <T> T?.ifNotNull(block: (T) -> Unit) {
    if (this != null) block(this)
}

// 对于频繁调用的简单扩展,使用内联
inline fun String?.isNullOrEmpty(): Boolean {
    return this == null || isEmpty()
}

总结

可空类型扩展函数的优点:

  1. 提升代码可读性 - 将空检查逻辑封装在扩展中
  2. 减少样板代码 - 避免重复的 if (x != null) 检查
  3. 增强表达力 - 创建领域特定的安全操作
  4. 支持链式调用 - 在可能为空的链式操作中保持安全

使用建议:

  • 为常用操作创建可空扩展
  • 提供合理的默认返回值
  • 保持函数纯函数特性(无副作用)
  • 合理使用内联优化性能

通过合理使用可空类型扩展函数,可以显著提高 Kotlin 代码的安全性和可维护性。

相关推荐
FungLeo5 小时前
FengCMS · PHP+MySQL 升级实录 · 危险默认值之殇:root/123456、认证码 8888 写进配置加载器
android·mysql·php·安全加固·fengcms
yz_aiks5 小时前
Termux 使用教程:把安卓手机变成随身 Linux(装 Python、SSH 远程、跑自动化脚本)
android·linux·python·智能手机·ssh·termux
booboosui13 小时前
编号没变,消息还是来了:Mac 端通知读取漏第二条的原因
android
雨白1 天前
单例设计模式:从 Java/Kotlin 实现到 Android 实战
android
hai_android1 天前
一行 asLiveData,背后是一座生命周期的桥
android·java·kotlin
阿杰m1 天前
Android源码第二十三章:Telephony、RIL 与 IMS——来电怎么到应用?
android
booboosui1 天前
没人认领 .md:安卓把报告交给了音乐播放器打开
android
用户60709759149062 天前
AOSP 14 OTA 升级指导(四):update_engine 内部机制——Action 流水线与写盘
android
恋猫de小郭2 天前
Jetpack Compose 1.13 发布,憋了这么久终有交代了
android·前端·flutter
JMchen1232 天前
【Android 性能优化实战 60 讲】12 异步 Inflate 实战与痛击:源码拆解原生瓶颈,手写增强版布局预加载框架
android·性能优化·实战·启动优化·异步inflate·x2c