henrik
henrik

Reputation: 95

Creating a map with values containing generics

I want to create a map with a key being a single object and a value being many objects, some containing generics. Is there a concise way to do this in Kotlin? I've used data classes in the past, but haven't found a way to make that work with generics.

Thanks!

Edit: Here's an example:

class SomeClass<E> {
    data class Data(val str: String, val int: Int, val e: E) //the last value is invalid

    val map: MutableMap<String, Data> = mutableMapOf()

}

Upvotes: 1

Views: 1528

Answers (1)

Robin
Robin

Reputation: 3892

Working from your example, this should work for you.

data class Data<E>(val str: String, val int: Int, val e: E)

class SomeClass<E> {

    val map: MutableMap<String, Data<E>> = mutableMapOf()

}

I'm defining Data as an external, generic class, and use that inside the actual class.

Edit: Actually, you don't even need to move the data class outside of the outer class:

class SomeClass<E> {
    data class Data<T>(val str: String, val int: Int, val e: T)

    val map: MutableMap<String, Data<E>> = mutableMapOf()

}

Upvotes: 2

Related Questions