# Smart Cast on type of KClass\<T\> to T?

**URL:** <https://discuss.kotlinlang.org/t/smart-cast-on-type-of-kclass-t-to-t/3799>\
**Category:** Uncategorized\
**Created:** [July 19, 2017, 11:06am UTC](https://discuss.kotlinlang.org/t/smart-cast-on-type-of-kclass-t-to-t/3799 "2017-07-19T11:06:24Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Tim\_van\_der\_Leeuw.1](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/tim_van_der_leeuw.1/32/9155_2.png) [@Tim\_van\_der\_Leeuw.1](https://discuss.kotlinlang.org/u/Tim_van_der_Leeuw.1)\
**Post date:** [July 19, 2017, 11:06am UTC](https://discuss.kotlinlang.org/t/smart-cast-on-type-of-kclass-t-to-t/3799/1 "2017-07-19T11:06:24Z")

</div>

I want to create a function to create class instances, based on the type of class that I pass as the function parameter.

I wrote the function like this:

```
class Foo
class Bar

private fun <T : Any> createDummyInstance(name: String, type: KClass<T>): T {
    val result: T = when (type) {
        Foo::class -> Foo()
        Bar::class -> Bar()
        String::class -> when (name) {
            "baseUrl" -> "http://localhost:8080/"
            else -> throw IllegalArgumentException("Don't know String property '$name'")
        }
        else -> throw IllegalArgumentException("Can't create instance of class ${type.simpleName}")
    } as T
    return result
}

```

At the end, I need to cast the result “as T” otherwise there’s a compiler error. The functions createTestShift() and createTestUser() return an instance of classes Shift and ApiUser respectively and the String case obviously returns a String instance.  
Why cannot the compiler smart cast this? How should I write code like this, so that I do not need the explicit cast to T?

---

<div class="post-metadata">

**Author:** ![udalov](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/udalov/32/5679_2.png) [@udalov](https://discuss.kotlinlang.org/u/udalov)\
**Post date:** [July 19, 2017, 6:35pm UTC](https://discuss.kotlinlang.org/t/smart-cast-on-type-of-kclass-t-to-t/3799/2 "2017-07-19T18:35:45Z")

</div>

The compiler can’t deduce that `T` is `Foo` from the fact that `type` is `Foo::class` because it’s not that smart yet. If you think this is worth supporting in the language, feel free to create an issue. However, I don’t think the compiler _should_ deduce this because one can come up with examples of valid code (with unchecked casts) where this condition won’t hold.

The intended way is exactly how you’ve written + maybe suppression of the “unchecked cast” warning.
