# Unexpected type inference behaviour with definitely not-nullable type parameters

**URL:** <https://discuss.kotlinlang.org/t/unexpected-type-inference-behaviour-with-definitely-not-nullable-type-parameters/27009>\
**Category:** Language Design\
**Created:** [June 28, 2023, 11:39am UTC](https://discuss.kotlinlang.org/t/unexpected-type-inference-behaviour-with-definitely-not-nullable-type-parameters/27009 "2023-06-28T11:39:38Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ctsk](https://avatars.discourse-cdn.com/v4/letter/c/13edae/32.png) [@ctsk](https://discuss.kotlinlang.org/u/ctsk)\
**Post date:** [June 28, 2023, 11:39am UTC](https://discuss.kotlinlang.org/t/unexpected-type-inference-behaviour-with-definitely-not-nullable-type-parameters/27009/1 "2023-06-28T11:39:38Z")

</div>

I’ll lead with the code:

```kotlin
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) {
            MyOption(null) 
        } else {
            MyOption(param)
        }
    }
}

```

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

---

<div class="post-metadata">

**Author:** ![derektom14](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/derektom14/32/7411_2.png) [@derektom14](https://discuss.kotlinlang.org/u/derektom14)\
**Post date:** [June 28, 2023, 4:38pm UTC](https://discuss.kotlinlang.org/t/unexpected-type-inference-behaviour-with-definitely-not-nullable-type-parameters/27009/2 "2023-06-28T16:38:03Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![broot](https://avatars.discourse-cdn.com/v4/letter/b/a88e57/32.png) [@broot](https://discuss.kotlinlang.org/u/broot)\
**Post date:** [June 28, 2023, 5:19pm UTC](https://discuss.kotlinlang.org/t/unexpected-type-inference-behaviour-with-definitely-not-nullable-type-parameters/27009/3 "2023-06-28T17:19:08Z")

</div>

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.
