Kotlin Delegates.notNull用法及代码示例

154 阅读1分钟

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

Delegates.notNull 所在包 kotlin.properties.Delegates.notNull,其相关用法介绍如下:

用法:

fun <T : Any> notNull(): ReadWriteProperty<Any?, T>

返回具有非 null 值的读/写属性的属性委托,该值不是在对象构造期间而是在以后初始化。在分配初始值之前尝试读取属性会导致异常。

示例代码:

import kotlin.properties.Delegates

import kotlin.test.*

fun main(args: Array<String>) {
    //sampleStart
    var max: Int by Delegates.notNull()

    // println(max) // will fail with IllegalStateException

    max = 10
    println(max) // 10
    //sampleEnd
}

// 输出
10

相关方法