kotlin - 如何将类型标记为非空?

标签 kotlin nullable non-nullable

我想要一个通用方法(或类),其行为如下:

val instanceS = MyCoolClass<String?>()
instanceS.someMethod("some not null string") //compiles
instanceS.someMethod(null) //doesn´t compile
val instanceS2 = MyCoolClass<String>()
//Exactly the same
instanceS2.someMethod("some not null string") //compiles
instanceS2.someMethod(null) //doesn´t compile

正如我可以将泛型类型(已经可以为空)标记为可为空,如下所示:

fun <T> doSomething():T? = ...

没有东西可以将类型(已经可以为不可为空)标记为不可为空吗?

fun <T> doSomething():T! = ... //this is not valid syntax

最佳答案

绝对非空类型用 T & Any 表示。此类型是 T 的不可空版本如果T恰好表示可为 null 的类型。

fun <T> doSomething(someInput: T, someNonNullDefault: T & Any): T & Any {
    return someInput ?: someNonNullDefault
}

这个例子当然可以这样实现:

fun <T: Any> doSomething(someInput: T?, someNonNullDefault: T): T {
    return someInput ?: someNonNullDefault
}

但是如果<T>范围仅限于类,而不是您想要的示例代码中的函数,那么此功能有更多用处。

此功能需要 Kotlin 1.7.0 或更高版本。

关于kotlin - 如何将类型标记为非空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75684939/

相关文章:

android - 如何使用 CameraX 将 PreviewView 纵横比与捕获的图像匹配

java - 当 lambda 可能返回 null 时,如何使 IntelliJ IDEA 发出警告?

java - 在 Kotlin 中测试非空参数

java - 将 Jackson 与具有私有(private) Builder 的不可变类一起使用

android - 无法在 Kotlin 中构建发布版本

datetime - Azure 表 'Merge' 不会替换传递值为 null 的字段(例如 :Nullable<Date> field) C#

java - 基于注解的空值分析——警告只出现在数组参数中

c# - 如何将 "any non-nullable type"指定为泛型类型参数约束?

flutter 错误 : "A value of type ' Null' can't be assigned to a variable of type 'Product' ."

list - Kotlin 从列表中取出 x 个元素但首先删除最小的数字