Andrey Kachow
Andrey Kachow

Reputation: 1126

TypeVariable(V) Required in Mutable Map assignment in Kotlin. Cannot put the value from a map to itself

The following example is a simplified version of what I am trying to do in my application.

fun main() {
    val test: MutableMap<Int, String> = mutableMapOf(
        1 to "Apple",
    )
    test[2] = test[1]  // test[1] has incorrect type.
}

The code doesn't compile. IntelliJ gives the following hint:

Type mismatch.

    Required:   TypeVariable(V)

    Found:      String?

I don't understand what a TypeVariable is. but when I provide a default value the error disappears

test[2] = test[1] ?: "Grape"

Why the required type is TypeVariable(V), not String, and what exactly is it? What to do if there's no default value for my application purposes?

Upvotes: 9

Views: 8674

Answers (1)

lukas.j
lukas.j

Reputation: 7163

... = test[1]

returns a String? as the hint showed you. But test is a MutableMap of <Int, String>, which means you need to assign a String:

... = test[1]!!

Of course this will only work if 1 is a valid key in test. Otherwise your code with the null safety operator is the way to go:

... = test[1] ?: "default value"

Upvotes: 7

Related Questions