【问题标题】:Generics in Kotlin: how does this compile?Kotlin 中的泛型:如何编译?
【发布时间】:2020-07-03 20:08:54
【问题描述】:
    fun <E> Set<E>.containsAny(vararg elements: E) = intersect(elements.toSet()).isNotEmpty()

    fun test() {
        emptySet<String>().containsAny(1, Unit)
    }

这在 Kotlin 中编译,为什么?

【问题讨论】:

    标签: generics kotlin type-projection


    【解决方案1】:

    因为预计的参数类型将是&lt;Any&gt;。并且测试函数可以替换为:

    fun test() {
            emptySet<String>().containsAny<Any>(1, Unit)
        }
    

    要使函数正常工作,您必须显式传递类型:

    fun test() {
            emptySet<String>().containsAny<String>(1, Unit) // Does not compile
        }
    

    或者如果可能的话,指定较少的泛型类型:

    fun Set<Permission>.containsAny(vararg elements: Permission) = intersect(elements.toSet()).isNotEmpty()
    

    【讨论】:

      猜你喜欢
      • 2011-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 2017-12-06
      • 2021-01-22
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多