简体   繁体   English

TypeVariable(V) 在 Kotlin 中的可变 Map 分配中需要。 无法将 map 中的值放入自身

[英]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: IntelliJ 给出以下提示:

Type mismatch.

    Required:   TypeVariable(V)

    Found:      String?

I don't understand what a TypeVariable is.我不明白 TypeVariable 是什么。 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?为什么所需的类型是TypeVariable(V) ,而不是String ,它到底是什么? What to do if there's no default value for my application purposes?如果我的应用程序没有默认值怎么办?

... = 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是一个<Int, String>的MutableMap,也就是说你需要分配一个String:

... = test[1]!!

Of course this will only work if 1 is a valid key in test .当然,这只有在 1 是test中的有效键时才有效。 Otherwise your code with the null safety operator is the way to go:否则,您使用 null 安全运算符的代码是通往 go 的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM