英文:
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<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
答案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 & 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论