以下示例是我在应用程序中尝试执行的操作的简化版本。
fun main() {
val test: MutableMap<Int, String> = mutableMapOf(
1 to "Apple",
)
test[2] = test[1] // test[1] has incorrect type.
}
Run Code Online (Sandbox Code Playgroud)
该代码无法编译。IntelliJ 给出了以下提示:
Type mismatch.
Required: TypeVariable(V)
Found: String?
Run Code Online (Sandbox Code Playgroud)
我不明白 TypeVariable 是什么。但是当我提供默认值时错误消失
test[2] = test[1] ?: "Grape"
Run Code Online (Sandbox Code Playgroud)
为什么所需的类型是TypeVariable(V),String而不是 ,它到底是什么?如果我的应用程序没有默认值该怎么办?
... = test[1]
Run Code Online (Sandbox Code Playgroud)
返回一个字符串?正如提示所示。但是test是一个<Int, String>的MutableMap,这意味着你需要分配一个String:
... = test[1]!!
Run Code Online (Sandbox Code Playgroud)
当然,只有当 1 是test中的有效密钥时,这才有效。否则,使用 null 安全运算符的代码就是正确的选择:
... = test[1] ?: "default value"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6580 次 |
| 最近记录: |