【问题标题】:Type mismatch: inferred type is T but kotlin.Any was expected类型不匹配:推断类型为 T 但预期为 kotlin.Any
【发布时间】:2016-04-20 13:37:06
【问题描述】:

我有以下代码:

val map = HashMap<Int, Any>()
fun <T> test(t: T) = map.put(0, t) // Type mismatch: inferred type is T but kotlin.Any was expected

但是every Kotlin class has Any as a superclass,为什么会出现这个错误?

【问题讨论】:

    标签: kotlin


    【解决方案1】:

    T 在此函数中可以为空。您应该明确指定它不可为空。

    fun <T : Any> test(t: T) = map.put(0, t)
    

    【讨论】:

    • 补充一点,裸&lt;T&gt; 的默认绑定是Any?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    相关资源
    最近更新 更多