gpt4 book ai didi

kotlin - 在 Kotlin 中只返回 null 的函数

转载 作者:IT老高 更新时间:2023-10-28 13:42:16 28 4
gpt4 key购买 nike

是否可以声明一个只返回 null 的函数?不幸的是,你不能在返回类型部分写 null。返回值应该是 null 而不是 Unit,以便它可以与可为空的运算符一起使用。

最佳答案

正如评论中所建议的,Nothing? 应该是这样一个函数的返回类型:

fun alwaysNull(): Nothing? = null

documentation状态:

[...] Another case where you may encounter this type is type inference. The nullable variant of this type, Nothing?, has exactly one possible value, which is null. If you use null to initialize a value of an inferred type and there's no other information that can be used to determine a more specific type, the compiler will infer the Nothing? type:

val x = null           // 'x' has type `Nothing?`
val l = listOf(null) // 'l' has type `List<Nothing?>

关于kotlin - 在 Kotlin 中只返回 null 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49215835/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com