# Cast with Generics, how to achieve this?

**URL:** <https://discuss.kotlinlang.org/t/cast-with-generics-how-to-achieve-this/1511>\
**Category:** Support\
**Created:** [March 4, 2016, 4:01pm UTC](https://discuss.kotlinlang.org/t/cast-with-generics-how-to-achieve-this/1511 "2016-03-04T16:01:52Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ronnin](https://avatars.discourse-cdn.com/v4/letter/r/aca169/32.png) [@ronnin](https://discuss.kotlinlang.org/u/ronnin)\
**Post date:** [March 4, 2016, 4:01pm UTC](https://discuss.kotlinlang.org/t/cast-with-generics-how-to-achieve-this/1511/1 "2016-03-04T16:01:52Z")

</div>

```
data class Message (var code: String, var msg: String, var data: Any) {
    fun addDataItem(dataItem: Any): Message {
        if (this.data is Collection<*>) {
            this.data = this.data as Collection<*> + dataItem // ok, but as-operation is essential
            return this
        }
        return this.copy(data = listOf(dataItem))
    } 

   fun addDataEntry(name: String, value: Any): Message {
        if (this.data is Map<*, *>) { // can reified to Map<String,Any> ?
          this.data = this.data as Map<*, *> + (name to value) // compiler error here
        }

       return this.copy(data = mapOf(name to value))
    }
}

```

the map operation in the fun addDataEntry() is simple, but I can’t figure out the right way to achieve.  
Thanks, forward

---

<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:** [March 4, 2016, 5:06pm UTC](https://discuss.kotlinlang.org/t/cast-with-generics-how-to-achieve-this/1511/2 "2016-03-04T17:06:46Z")

</div>

`Map<*, *>` is equivalent to `Map<out Any?, out Any?>` — an out-projection of the `Map<K, out V>` interface which is invariant on its `K` type parameter. And `plus` operator function expects the invariant `Map<K, out V>`.

So currently you need to cast the map to be invariant on its key as following:

```auto
this.data = this.data as Map<Any?, *> + (name to value)

```

This is unsafe cast, so you get a warning, but in this situation you can safely ignore or suppress it.

This seems to be unneeded limitation of the `plus` operator, and I believe we could fix it by making `plus` accept `Map<out K, out V>` as its receiver. I’ve opened an issue [KT-11301](https://youtrack.jetbrains.com/issue/KT-11301).
