kotlinnullablenon-nullable

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

Solution

  • 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.