Kotlin getOrNull用法及代码示例

本文方法及代码示例基于Kotlin 2.1.20 Released

getOrNull 所在包 kotlin.text.getOrNull,其相关用法介绍如下:

用法:

kotlin 复制代码
fun CharSequence.getOrNull(index: Int): Char?

如果 index 超出此字符序列的范围,则返回给定 indexnull 处的字符。

示例代码:

kotlin 复制代码
import kotlin.test.*

fun main(args: Array<String>) {
    //sampleStart
    val list = listOf(1, 2, 3)
    println(list.getOrNull(0)) // 1
    println(list.getOrNull(2)) // 3
    println(list.getOrNull(3)) // null

    val emptyList = emptyList<Int>()
    println(emptyList.getOrNull(0)) // null
    //sampleEnd
}

// 输出
1
3
null
null

相关方法

相关推荐
哑巴湖小水怪6 小时前
Android的架构是四层还是五层
android·架构
2501_916008898 小时前
深入解析iOS应用启动性能优化策略与实践
android·ios·性能优化·小程序·uni-app·cocoa·iphone
美狐美颜SDK开放平台9 小时前
短视频/直播双场景美颜SDK开发方案:接入、功能、架构详解
android·ios·美颜sdk·第三方美颜sdk·视频美颜sdk
untE EADO9 小时前
在 MySQL 中使用 `REPLACE` 函数
android·数据库·mysql
iblade10 小时前
Android CLI And Skills 3x faster
android
阿巴斯甜11 小时前
SharedUnPeekLiveData和UnPeekBus的区别:
android
阿巴斯甜11 小时前
UnPeek-LiveData的使用:
android
我就是马云飞12 小时前
我废了!大厂10年的我面了20家公司,面试官让我回去等通知!
android·前端·程序员
limuyang213 小时前
在 Android 上用上原生的 xxHash,性能直接拉满
android
Fate_I_C13 小时前
ViewModel 的生命周期与数据保持
android·kotlin