# Nullable generic parameter

**URL:** <https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553>\
**Category:** Uncategorized\
**Created:** [April 26, 2018, 7:30am UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553 "2018-04-26T07:30:04Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![vagran](https://avatars.discourse-cdn.com/v4/letter/v/b5ac83/32.png) [@vagran](https://discuss.kotlinlang.org/u/vagran)\
**Post date:** [April 26, 2018, 7:30am UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/1 "2018-04-26T07:30:04Z")

</div>

I searched across many similar questions, but still cannot get an answer for this simple example. The example is just one possible case among many others with the same root cause.

```
class C<T> {
    private var a: T? = null
    private var b: T? = null
    private var isCurrentA = true

    fun SetA(x: T)
    {
        a = x
        isCurrentA = true
    }

    fun SetB(x: T)
    {
        b = x
        isCurrentA = false
    }

    fun GetCurrent(): T
    {
        return if (isCurrentA) a!! else b!! //<<< NPE here
    }
}

@Test
fun F()
{
    val c = C<Int?>()
    c.SetA(null)
    assertNull(c.GetCurrent())
}

```

The code is synthetic and simplified to illustrate the problem. Null pointer exception is thrown if trying to call GetCurrent() method. What is the proper implementation of such class?

---

<div class="post-metadata">

**Author:** ![darksnake](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/darksnake/32/2479_2.png) [@darksnake](https://discuss.kotlinlang.org/u/darksnake)\
**Post date:** [April 26, 2018, 7:46am UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/2 "2018-04-26T07:46:14Z")

</div>

I don’t really understand, what you are trying to do. It has nothing to do with generics. You explicitly are setting `a` to `null` twice. Once in variable declaration, and second one in `c.SetA(null)`, and then calling `a!!` which is by default throwing exception on nulls.

Also your code style clearly showed, that you probably should spend some time reading documentation. Method names should start with lower case letter.

---

<div class="post-metadata">

**Author:** ![forinil2](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/forinil2/32/2465_2.png) [@forinil2](https://discuss.kotlinlang.org/u/forinil2)\
**Post date:** [April 26, 2018, 7:46am UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/3 "2018-04-26T07:46:16Z")

</div>

This how I solved it:

```kotlin
fun main(args: Array<String>) {
    f()
}

class C<T> {
    private var a: T? = null
    private var b: T? = null
    private var isCurrentA = true

    fun setA(x: T?)
    {
        a = x
        isCurrentA = true
    }

    fun setB(x: T?)
    {
        b = x
        isCurrentA = false
    }

    fun getCurrent(): T?
    {
        return if (isCurrentA) a else b
    }
}

fun f()
{
    val c = C<Int>()
    c.setA(null)
    println(c.getCurrent())
}

```

This code prints null as expected and does not throw NPE

---

<div class="post-metadata">

**Author:** ![darksnake](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/darksnake/32/2479_2.png) [@darksnake](https://discuss.kotlinlang.org/u/darksnake)\
**Post date:** [April 26, 2018, 7:48am UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/4 "2018-04-26T07:48:15Z")

</div>

In this case you do not need to specify generic type as `<Int?>` simple `<Int>` will suffice, because you declared type as nullable `T?` everywhere in class.

---

<div class="post-metadata">

**Author:** ![forinil2](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/forinil2/32/2465_2.png) [@forinil2](https://discuss.kotlinlang.org/u/forinil2)\
**Post date:** [April 26, 2018, 7:50am UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/5 "2018-04-26T07:50:38Z")

</div>

Thanks, I updated the code.

---

<div class="post-metadata">

**Author:** ![vagran](https://avatars.discourse-cdn.com/v4/letter/v/b5ac83/32.png) [@vagran](https://discuss.kotlinlang.org/u/vagran)\
**Post date:** [April 26, 2018, 7:51am UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/6 "2018-04-26T07:51:35Z")

</div>

Setting null in initialization is just to set some default value here, actually value is not present at this moment, until Set() is called. The SetA() with null is just an example which illustrates possibility of setting null since my type parameter is nullable (Int?). After that the value is considered present and is null in this case, and somehow should be returned by GetCurrent() method.

---

<div class="post-metadata">

**Author:** ![vagran](https://avatars.discourse-cdn.com/v4/letter/v/b5ac83/32.png) [@vagran](https://discuss.kotlinlang.org/u/vagran)\
**Post date:** [April 26, 2018, 7:57am UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/7 "2018-04-26T07:57:44Z")

</div>

No, it does not solve the problem. I want return value to have the same nullability as the type parameter, that’s one of the main points, otherwise it seems that nullability in generic type parameters is not really a first-class-citizen, and cannot really be abstracted of.

---

<div class="post-metadata">

**Author:** ![darksnake](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/darksnake/32/2479_2.png) [@darksnake](https://discuss.kotlinlang.org/u/darksnake)\
**Post date:** [April 26, 2018, 8:01am UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/8 "2018-04-26T08:01:09Z")

</div>

Then you should use `T` instead of `T?` everywhere, but then you can’t set the value to `null` in initializator, because compiler does not know whether `T` is nullable or not.

---

<div class="post-metadata">

**Author:** ![vagran](https://avatars.discourse-cdn.com/v4/letter/v/b5ac83/32.png) [@vagran](https://discuss.kotlinlang.org/u/vagran)\
**Post date:** [April 26, 2018, 8:08am UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/9 "2018-04-26T08:08:33Z")

</div>

Yes, that’s the problem (I cannot set null and I also cannot left it uninitialized too), and I am asking for solution.  
One more example which may be more clear is implementing analogue of Java Optional class which has very similar principle. But it also should properly handle null value in contrast with Java 8 implementation (so that they are separate states - “None” and “Null set”). And again its get() method result type should have the same nullability as the passed type parameter.  
Actually I have implemented such class but I forced to use interface and different implementation classes for present and not-present values. I think it’s quite big overhead for such simple thing which is needed just because of the language constraints, and I’m also looking for simpler solution for that.

---

<div class="post-metadata">

**Author:** ![Oliver\_Plohmann](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/oliver_plohmann/32/2398_2.png) [@Oliver\_Plohmann](https://discuss.kotlinlang.org/u/Oliver_Plohmann)\
**Post date:** [April 26, 2018, 8:54am UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/10 "2018-04-26T08:54:12Z")

</div>

I would say that this should not compile:

```
val c = C<Int?>()

```

Because class C was defined like this:

```
class C<T> {
    // ...
}

```

and not like that:

```
class C<T?> {
    // ...
}

```

(note the ‘?’ in the generics parameter list)

---

<div class="post-metadata">

**Author:** ![vagran](https://avatars.discourse-cdn.com/v4/letter/v/b5ac83/32.png) [@vagran](https://discuss.kotlinlang.org/u/vagran)\
**Post date:** [April 26, 2018, 9:00am UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/11 "2018-04-26T09:00:42Z")

</div>

No, it compiles. If you want to prevent passing nullable types, it should be declared like this:

```
class C<T: Any> {
    //...
}

```

By default it is “class C\<T: Any?\>”. In my case I want both nullable and not-nullable, so default works.

---

<div class="post-metadata">

**Author:** ![vagran](https://avatars.discourse-cdn.com/v4/letter/v/b5ac83/32.png) [@vagran](https://discuss.kotlinlang.org/u/vagran)\
**Post date:** [April 26, 2018, 10:32am UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/12 "2018-04-26T10:32:35Z")

</div>

Another code example for mentioned Optional class, which might be better understandable. It also is mutable to be consistent with the first example.

```
class MutableOptional<T> {
    private var value: T? = null
    private var isSet: Boolean = false

    fun set(value: T)
    {
        this.value = value
        isSet = true
    }

    fun unset()
    {
        isSet = false
        value = null
    }

    fun get(): T
    {
        if (!isSet) {
            throw Error("Value not set")
        }
        return value!! // <<< NPE here
    }
}

fun f()
{
    val opt = MutableOptional<Int?>()
    opt.set(null)
    assertNull(opt.get())
}

```

---

<div class="post-metadata">

**Author:** ![forinil2](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/forinil2/32/2465_2.png) [@forinil2](https://discuss.kotlinlang.org/u/forinil2)\
**Post date:** [April 26, 2018, 11:07am UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/13 "2018-04-26T11:07:20Z")

</div>

OK, in this case, I propose the following:

```kotlin
class MutableOptional<T> {
    private var value: T? = null
    private var isSet: Boolean = false

    fun set(value: T)
    {
        this.value = value
        isSet = true
    }

    fun unset()
    {
        isSet = false
        value = null
    }

    fun get(): T?
    {
        if (!isSet) {
            throw Error("Value not set")
        }
        return value
    }
}

fun f()
{
    val opt = MutableOptional<Int?>()
    opt.set(null)
    println(opt.get())
}

```

---

<div class="post-metadata">

**Author:** ![vagran](https://avatars.discourse-cdn.com/v4/letter/v/b5ac83/32.png) [@vagran](https://discuss.kotlinlang.org/u/vagran)\
**Post date:** [April 26, 2018, 11:13am UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/14 "2018-04-26T11:13:40Z")

</div>

Again, you changed the return type of get(). After that I will need every time in the code use !! operator where I am sure it is non-nullable (which is compiler job by design of all of this “null-safety” feature in Kotlin).

---

<div class="post-metadata">

**Author:** ![forinil2](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/forinil2/32/2465_2.png) [@forinil2](https://discuss.kotlinlang.org/u/forinil2)\
**Post date:** [April 26, 2018, 11:18am UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/15 "2018-04-26T11:18:53Z")

</div>

You cannot return null from a method if the return parameter is not declared nullable.There is no way aorund this, nor should there be, otherwise the compiler would have to determine null safety on a case-by-case basis and not by simply inspecting the return type. I shudder to think how long the compilation with such an compiler would take.

---

<div class="post-metadata">

**Author:** ![vagran](https://avatars.discourse-cdn.com/v4/letter/v/b5ac83/32.png) [@vagran](https://discuss.kotlinlang.org/u/vagran)\
**Post date:** [April 26, 2018, 11:22am UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/16 "2018-04-26T11:22:18Z")

</div>

But T is nullable type itself (Int?) in this instantiation. I could return null if “value” member would be of type T. But in this case I am not able to provide default initialization for this member.

---

<div class="post-metadata">

**Author:** ![forinil2](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/forinil2/32/2465_2.png) [@forinil2](https://discuss.kotlinlang.org/u/forinil2)\
**Post date:** [April 26, 2018, 11:46am UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/17 "2018-04-26T11:46:23Z")

</div>

Well, technically speaking you could do it like this:

```kotlin
class MutableOptional<T> {
    private var _value: T? = null
    private var value: T by Delegate()
    private var isSet: Boolean = false

    fun set(value: T)
    {
        this.value = value
        isSet = true
    }

    @Suppress("UNCHECKED_CAST")
    fun unset()
    {
        value = null as T
    }

    fun get(): T
    {
        return value
    }

    class Delegate<T> {
        @Suppress("UNCHECKED_CAST")
        operator fun getValue(thisRef: MutableOptional<T>, property: KProperty<*>): T {
            println("$thisRef, thank you for delegating '${property.name}' to me!")
            if (!thisRef.isSet) {
                throw Error("Value not set")
            }
            return thisRef._value as T
        }

        operator fun setValue(thisRef: MutableOptional<T>, property: KProperty<*>, value: T) {
            println("$value has been assigned to '${property.name}' in $thisRef.")
            thisRef.isSet = true
            thisRef._value = value
        }
    }
}

fun f()
{
    val opt = MutableOptional<Int?>()
    opt.set(null)
    println(opt.get())
}

```

but it looks ugly to me.

---

<div class="post-metadata">

**Author:** ![vagran](https://avatars.discourse-cdn.com/v4/letter/v/b5ac83/32.png) [@vagran](https://discuss.kotlinlang.org/u/vagran)\
**Post date:** [April 26, 2018, 11:55am UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/18 "2018-04-26T11:55:03Z")

</div>

Oh, I did not think about cast possibility between T? and T. In this case it can be simpler:

```
    @Suppress("UNCHECKED_CAST")
    fun get(): T
    {
        if (!isSet) {
            throw Error("Value not set")
        }
        return value as T
    }

```

That looks like working solution.

---

<div class="post-metadata">

**Author:** ![cabman](https://avatars.discourse-cdn.com/v4/letter/c/50afbb/32.png) [@cabman](https://discuss.kotlinlang.org/u/cabman)\
**Post date:** [April 29, 2018, 1:48pm UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/19 "2018-04-29T13:48:57Z")

</div>

I think the main question to vagran was: what should happened BEFORE any value set?  
Once the answer is Exception it was easy to come to final solution.

However I see that multiple people in this discussion (including vagran) are confused about nullable classes. The main idea is that and \<T?\> are two different classes (unlike T!!) and casting is the way to convert more generic to more specific.

---

<div class="post-metadata">

**Author:** ![darksnake](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/darksnake/32/2479_2.png) [@darksnake](https://discuss.kotlinlang.org/u/darksnake)\
**Post date:** [April 29, 2018, 4:40pm UTC](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553/20 "2018-04-29T16:40:24Z")

</div>

The problem is kotlin is explicitly made to avoid solutions like the one @vagran proposed. One should plan the architecture the way you either use nullable or not.  
The problem with late initialization of variables could be solved without meddling with generics. First variant is `lateinit var`. It could be used when you are sure that value will be assigned. Another way is nun-nulable front to nulable field:

```kotlin
private val nullable: T? = null
val nonNulable: T
  get() = nullable ?: throw RuntimeException(...)

```

[Next page](https://discuss.kotlinlang.org/t/nullable-generic-parameter/7553.md?page=2)
