【问题标题】: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】:
因为预计的参数类型将是<Any>。并且测试函数可以替换为:
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()