Unexpected type inference behaviour with definitely not-nullable type parameters

I’ll lead with the code:

class MyOption<V: Any>(private var value: V?) {
    fun hasValue(): Boolean {
        return value == null

    fun clear() {
        value = null

    fun set(value: V) {
        this.value = value

    fun get(): V {
        return value!!
class SomeContainer<T: Any?>(private val param: T) {
    fun hasValue(): MyOption<T & Any> {
        // return MyOption<T & Any>(param); // DOESN'T Work, compiler complains

        // works fine
        return if (param == null) {
        } else {

Can someone help me understand why the code in SomeContainer<T>::hasValue only works with the “if” checking for null?

Because T may itself be null, param is nullable, and MyOption(param) would be of type MyOption<T>, not MyOption<T & Any>. When you confirm that param is not null, we also confirm that it is of type Any instead of Any?, so MyOption(param) is a MyOption<T & Any>.

I think the question is why it can’t be treated the same as MyOption(null) which is considered safe, because the constructor of MyOption receives V?.

I think this is just a limitation in the implementation of generics in Kotlin, but I can’t explain it better.