如何将类型标记为非空?

huangapple go评论54阅读模式
英文:

How to mark a type as not null?

问题

I want a generic method (or class) to behave something like this:

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

Just as I can mark a generic type (that can already be nullable) to be nullable like this:

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

Isn't there something to mark a type (that can already be non-nullable) to be non-nullable??

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

I want a generic method (or class) to behave something like this:

val instanceS = MyCoolClass&lt;String?&gt;()
instanceS.someMethod(&quot;some not null string&quot;) //compiles
instanceS.someMethod(null) //doesn&#180;t compile
val instanceS2 = MyCoolClass&lt;String&gt;()
//Exactly the same
instanceS2.someMethod(&quot;some not null string&quot;) //compiles
instanceS2.someMethod(null) //doesn&#180;t compile

Just as I can mark a generic type (that can already be nullable) to be nullable like this:

fun &lt;T&gt; doSomething():T? = ...

Isn't there something to mark a type (that can already be non nullable) to be non nullable??

fun &lt;T&gt; doSomething():T! = ... //this is not valid syntax

答案1

得分: 2

A definitely not-null type is denoted by using T & Any. This type is the non-nullable version of T if T happens to represent a nullable type.

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

This example could of course be achieved like this:

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

but if <T> is scoped to the class rather than the function like in your sample code of what you want, then this feature has a lot more usefulness.

This feature requires Kotlin 1.7.0 or higher.

英文:

A definitely not-null type is denoted by using T &amp; Any. This type is the non-nullable version of T if T happens to represent a nullable type.

fun &lt;T&gt; doSomething(someInput: T, someNonNullDefault: T &amp; Any): T &amp; Any {
    return someInput ?: someNonNullDefault
}

This example could of course be achieved like this:

fun &lt;T: Any&gt; doSomething(someInput: T?, someNonNullDefault: T): T {
    return someInput ?: someNonNullDefault
}

but if &lt;T&gt; is scoped to the class rather than the function like in your sample code of what you want, then this feature has a lot more usefulness.

This feature requires Kotlin 1.7.0 or higher.

huangapple
  • 本文由 发表于 2023年3月9日 20:56:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75684939.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定