# Trouble converting String to Enum with generics

**URL:** https://discuss.kotlinlang.org/t/trouble-converting-string-to-enum-with-generics/7716
**Category:** Support
**Created:** [May 7, 2018, 3:08pm UTC](https://discuss.kotlinlang.org/t/trouble-converting-string-to-enum-with-generics/7716 "2018-05-07T15:08:35Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![dmstocking](https://avatars.discourse-cdn.com/v4/letter/d/73ab20/32.png) [@dmstocking](https://discuss.kotlinlang.org/u/dmstocking)
#### Post date: [May 7, 2018, 3:08pm UTC](https://discuss.kotlinlang.org/t/trouble-converting-string-to-enum-with-generics/7716/1 "2018-05-07T15:08:35Z")

</div>

So I am trying to convert String to Enum via an inline reified extension function. The only problem is that type inference doesn’t work when the enum is nullable. Currently I have

```
inline fun <reified T: Enum<T>> String?.toEnumOrNull(): T? {
    if (this == null) {
        return null
    }

    return try {
        enumValueOf<T>(this)
    } catch (e: IllegalArgumentException) {
        null
    }
}

```

This works great when T is non null AKA not T?. But when it is T?, I have to specify the enum type.

```
val red: String? = "red"
val r1: Color = red.toEnum() // works
val r2: Color? = red.toEnumOrNull() // error
val r3: Color? = red.toEnumOrNull<Color>() // works

```

Has anyone else tried to do this?

---

<div class="post-metadata">

### Author: ![ilya.gorbunov](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/ilya.gorbunov/32/1645_2.png) [@ilya.gorbunov](https://discuss.kotlinlang.org/u/ilya.gorbunov)
#### Post date: [May 7, 2018, 3:30pm UTC](https://discuss.kotlinlang.org/t/trouble-converting-string-to-enum-with-generics/7716/2 "2018-05-07T15:30:22Z")

</div>

Yes, it was already reported as [https://youtrack.jetbrains.com/issue/KT-11218](https://youtrack.jetbrains.com/issue/KT-11218), feel free to star or vote that issue to receive updates on it.

---

<div class="post-metadata">

### Author: ![dmstocking](https://avatars.discourse-cdn.com/v4/letter/d/73ab20/32.png) [@dmstocking](https://discuss.kotlinlang.org/u/dmstocking)
#### Post date: [May 7, 2018, 3:40pm UTC](https://discuss.kotlinlang.org/t/trouble-converting-string-to-enum-with-generics/7716/3 "2018-05-07T15:40:09Z")

</div>

Gar. Sorry I didn’t find that myself. To bad there isn’t something we can do ourselves about it.
