Definitely non-nullable types

suggest change

T & Any is the type "T, but never null". It is called a definitely non-nullable type. You need it in generic code where T itself may be nullable, but a particular parameter or return value can't be:

fun <T> T.orThrow(message: String = "value is null"): T & Any =
    this ?: throw IllegalStateException(message)

If you call this on a String?, T is String? and the result is String.

Definitely non-nullable types were added in Kotlin 1.6.20 as an experimental feature and became stable in Kotlin 1.7. They need no opt-in or compiler flag. All examples here were compiled and run with Kotlin 2.4.21 on JDK 25.

Why T is nullable by default

A type parameter without a bound has the implicit upper bound Any? (see Generics). So fun <T> f(x: T) accepts String, Int, and also String? and Int?. Inside the function, a value of type T may be null, and so may a value the function returns as T.

That is usually what you want, but sometimes it gets in the way. This function skips nulls, so the value it returns can never be null, but its return type says otherwise:

fun <T> firstNonNull(items: List<T>): T {
    for (item in items) {
        if (item != null) return item
    }
    throw NoSuchElementException("no non-null element")
}

fun main() {
    val names: List<String?> = listOf(null, "Ann", null)
    val first = firstNonNull(names)   // inferred type: String?
    println(first.length)
}
problem.kt:11:18: error: only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type 'String?'.
    println(first.length)
                 ^

T is String?, so the return type is String?, and the caller has to deal with a null that can't happen.

The T & Any syntax

Change the return type to T & Any:

fun <T> firstNonNull(items: List<T>): T & Any {
    for (item in items) {
        if (item != null) return item   // smart cast: item is T & Any here
    }
    throw NoSuchElementException("no non-null element")
}

fun main() {
    val names: List<String?> = listOf(null, "Ann", null)
    val first = firstNonNull(names)   // inferred type: String
    println(first.length)

    val numbers = listOf(1, 2, 3)     // List<Int>
    val n: Int = firstNonNull(numbers)
    println(n)
}
3
1

Read T & Any as "a value that is both a T and an Any". Any is the non-nullable root type, so the intersection removes null from T. For T = String? it is String, and for a type that is already non-nullable, like Int, it is just Int.

You don't need a cast inside the function. After item != null, the compiler smart casts item from T to T & Any. The same happens with !!, ?: and requireNotNull():

fun <T> withElvis(value: T, fallback: T & Any): T & Any = value ?: fallback
fun <T> withRequire(value: T): T & Any = requireNotNull(value)
fun <T> withAssert(value: T): T & Any = value!!

fun main() {
    val s: String? = null
    println(withElvis(s, "fallback").length)
    println(withRequire("abc").length)
    println(withAssert<Int?>(7) + 1)
}
8
3
8

The compiler already used this type internally for smart casts before Kotlin 1.7. What 1.7 added is a way to write it in your own code.

Where it is allowed

& is not a general intersection type operator. Kotlin only accepts the exact form T & Any, where T is a type parameter whose bound is nullable. Every other use is a compile error:

fun <T> a(x: T & Any) = x                 // OK
fun <T> f(x: List<T & Any>) = x           // OK: as a type argument
class Box<T>(val value: T & Any)          // OK: in a class
fun <T> h(): Array<T & Any>? = null       // OK

fun <T : Any> b(x: T & Any) = x
fun <T> c(x: T & String) = x
fun d(x: String? & Any) = x
fun <T> e(x: (T & Any)?) = x
fun <T> g(x: T? & Any) = x
rules.kt:6:20: error: intersection types are supported only for definitely non-nullable types: left part must be a type parameter with nullable bounds.
fun <T : Any> b(x: T & Any) = x
                   ^
rules.kt:7:18: error: intersection types are supported only for definitely non-nullable types: right part must be non-nullable 'Any'.
fun <T> c(x: T & String) = x
                 ^^^^^^
rules.kt:8:10: error: intersection types are supported only for definitely non-nullable types: left part must be a type parameter with nullable bounds.
fun d(x: String? & Any) = x
         ^^^^^^^
rules.kt:9:14: error: definitely non-nullable type cannot be marked as nullable.
fun <T> e(x: (T & Any)?) = x
             ^^^^^^^^^^
rules.kt:10:14: error: intersection types are supported only for definitely non-nullable types: left part must be a type parameter with nullable bounds.
fun <T> g(x: T? & Any) = x
             ^^

In short:

Helper functions

Extension functions on T make good null helpers, because they work on any receiver, nullable or not:

fun <T> T.orThrow(message: String = "value is null"): T & Any =
    this ?: throw IllegalStateException(message)

fun <T> T.orElse(fallback: T & Any): T & Any = this ?: fallback

fun <T> elvis(x: T, fallback: T & Any) = x ?: fallback   // return type: T & Any

fun main() {
    val env: Map<String, String> = mapOf("HOME" to "/home/ann")
    val home: String = env["HOME"].orThrow("HOME not set")
    println(home.uppercase())

    val shell: String = env["SHELL"].orElse("/bin/sh")
    println(shell)

    val port: Int = elvis("8080".toIntOrNull(), 80)
    println(port)

    try {
        env["PATH"].orThrow("PATH not set")
    } catch (e: IllegalStateException) {
        println("error: ${e.message}")
    }
}
/HOME/ANN
/bin/sh
8080
error: PATH not set

elvis() has no declared return type. The compiler infers T & Any for x ?: fallback, because the left side only gets returned when it isn't null.

T & Any versus the T : Any bound

The older way to get a non-nullable T is the bound T : Any, which you can combine with T? where null is allowed. Many standard library functions are written like that, for example fun <T : Any> Iterable<T?>.filterNotNull(): List<T> and requireNotNull().

For a standalone function both styles do the same job:

fun <T> T.orThrow(): T & Any = this ?: throw IllegalStateException("null")
fun <T : Any> T?.orThrowOld(): T = this ?: throw IllegalStateException("null")

fun <R> generic(x: R) {
    val a: R & Any = x.orThrow()
    val b: R & Any = x.orThrowOld()     // T is inferred as R & Any
    println("$a $b")
}

fun main() {
    val s: String? = "text"
    val a: String = s.orThrow()
    val b: String = s.orThrowOld()
    println("$a $b")
    generic(42)
}
text text
42 42

The difference is what the bound does to callers. T : Any forbids nullable type arguments everywhere. T & Any leaves T alone and removes null in one place only. That matters when the type parameter belongs to a class, because then a member function can't put its own bound on it:

// T can be nullable: Settings<String?> is allowed
class Settings<T>(private val values: Map<String, T>) {
    fun get(key: String): T? = values[key]

    fun require(key: String): T & Any =
        values[key] ?: throw NoSuchElementException("missing or null: $key")
}

// T can't be nullable
class StrictSettings<T : Any>(private val values: Map<String, T>) {
    fun require(key: String): T =
        values[key] ?: throw NoSuchElementException("missing: $key")
}

fun main() {
    val raw: Map<String, String?> = mapOf("host" to "localhost", "proxy" to null)

    val settings = Settings(raw)            // Settings<String?>
    val host: String = settings.require("host")
    println(host.length)
    println(settings.get("proxy"))
    try {
        settings.require("proxy")
    } catch (e: NoSuchElementException) {
        println(e.message)
    }

    val strict = StrictSettings(raw.filterValues { it != null }.mapValues { it.value!! })
    println(strict.require("host"))
}
9
null
missing or null: proxy
localhost

Settings takes the map as it is, with null meaning "explicitly unset", and its require() still returns a plain String. StrictSettings can't hold that map at all. You have to clean it up first. StrictSettings<String?>(raw) fails with:

error: type argument is not within its bounds: type parameter 'T (of class StrictSettings<T : Any>)' must be subtype of 'Any', but actual: 'String?'.

Use the bound when null never makes sense for the type, for example a cache key or an event type. Use T & Any when the class or interface is fine with nullable T, but some of its members aren't.

Overriding Java methods

This is the case that T & Any was mainly added for. A generic Java interface can mark individual uses of T as not-null:

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public interface Store<T> {
    void save(@NotNull String key, @NotNull T value);
    @Nullable T load(@NotNull String key);
}

Kotlin reads @NotNull T as T & Any, and that type is part of the method signature. If you implement the interface with a plain T, the override doesn't match:

class MemoryStore<T> : Store<T> {
    private val map = HashMap<String, T>()
    override fun save(key: String, value: T) { map[key] = value }
    override fun load(key: String): T? = map[key]
}
interop_bad.kt:1:1: error: class 'MemoryStore' is not abstract and does not implement abstract member:
fun save(key: String, value: T & Any): Unit
class MemoryStore<T> : Store<T> {
^^^^^^^^^^^^^^^^^
interop_bad.kt:3:5: error: 'save' overrides nothing. Potential signatures for overriding:
fun save(key: String, value: T & Any): Unit
    override fun save(key: String, value: T) { map[key] = value }
    ^^^^^^^^

Before Kotlin 1.7 there was no way to write this signature. T : Any on the class would change the interface's contract, and T doesn't match it. Now you just copy the type from the error message:

class MemoryStore<T> : Store<T> {
    private val map = HashMap<String, T & Any>()

    override fun save(key: String, value: T & Any) {
        map[key] = value
    }

    override fun load(key: String): T? = map[key]
}

fun main() {
    val store = MemoryStore<String>()
    store.save("greeting", "hello")
    println(store.load("greeting"))
    println(store.load("missing"))
    // store.save("x", null)          // error: null cannot be a value of a non-null type 'String'

    val m = java.util.HashMap<String, String?>()
    m["a"] = "1"; m["b"] = null
    try {
        Printer.saveAll(MemoryStore<String?>(), m)
    } catch (e: NullPointerException) {
        println("NPE: ${e.message}")
    }
}

Printer.saveAll() is a Java method that calls store.save() for every entry of the map, ignoring the annotation:

public class Printer {
    public static <T> void saveAll(Store<T> store, java.util.Map<String, T> values) {
        values.forEach(store::save);
        System.out.println("saved " + values.size() + " values");
    }
}
hello
null
NPE: Parameter specified as non-null is null: method MemoryStore.save, parameter value

Even for a MemoryStore<String?>, Kotlin code can't pass null to save(). Java code can, but the Kotlin method checks its T & Any parameters at runtime, just like other non-nullable parameters, so the null is rejected at the boundary instead of ending up in the map.

The same works with JSpecify annotations, which Kotlin 2.x treats as strictly as its own types. In @NullMarked code, a type parameter declared as V extends @Nullable Object and used as @NonNull V becomes V & Any in Kotlin:

@NullMarked
public interface Cache<V extends @Nullable Object> {
    void put(String key, @NonNull V value);
    @Nullable V get(String key);
    V getOrDefault(String key, V fallback);
}
class MapCache<V> : Cache<V> {
    private val map = HashMap<String, V & Any>()
    override fun put(key: String, value: V & Any) { map[key] = value }
    override fun get(key: String): V? = map[key]
    override fun getOrDefault(key: String, fallback: V): V = map[key] ?: fallback
}

fun main() {
    val cache: Cache<String?> = MapCache()
    cache.put("a", "apple")
    // cache.put("b", null)        // error: null cannot be a value of a non-null type 'String'
    println(cache.get("a"))
    println(cache.getOrDefault("b", null))
}
apple
null

What it compiles to

On the JVM T & Any erases to the same type as T. The only differences are the runtime null check and a @NotNull annotation that Java tools and IDEs can read:

fun <T> plain(x: T): T = x
fun <T> nonNull(x: T & Any): T & Any = x
fun <T : Any> bounded(x: T): T = x
$ javap -c -p JvmKt
  public static final <T> T plain(T);
    Code:
         0: aload_0
         1: areturn
  public static final <T> T nonNull(T);
    Code:
         0: aload_0
         1: ldc           #12                 // String x
         3: invokestatic  #18                 // Method kotlin/jvm/internal/Intrinsics.checkNotNullParameter:(Ljava/lang/Object;Ljava/lang/String;)V
         6: aload_0
         7: areturn
  public static final <T> T bounded(T);
    Code:
         0: aload_0
         1: ldc           #12                 // String x
         3: invokestatic  #18                 // Method kotlin/jvm/internal/Intrinsics.checkNotNullParameter:(Ljava/lang/Object;Ljava/lang/String;)V
         6: aload_0
         7: areturn

nonNull and bounded compile to the same bytecode. Neither changes the erased signature, so switching a parameter between T, T & Any and T : Any doesn't break binary compatibility. It does change what Kotlin callers are allowed to pass, which is a source-level change.

A gap in variance checking

T & Any should follow the same variance rules as T: in an out T interface it belongs in return types, in an in T interface in parameters. Kotlin 2.4.21 checks T in the wrong position, but doesn't check T & Any:

interface Box<out T> {
    fun put(value: T & Any)      // should be rejected, but compiles in 2.4.21
}

class StringBox : Box<String> {
    override fun put(value: String) = println(value.length)
}

fun main() {
    val box: Box<Any> = StringBox()   // allowed because of 'out'
    try {
        box.put(42)
    } catch (e: ClassCastException) {
        println("ClassCastException")
    }
}
ClassCastException

Writing fun put(value: T) in the same interface is an error ("type parameter 'T' is declared as 'out' but occurs in 'in' position"). Don't rely on the missing check: put T & Any only where you could put T.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents