Generics in Kotlin: how does this compile?

48 views Asked by At
    fun <E> Set<E>.containsAny(vararg elements: E) = intersect(elements.toSet()).isNotEmpty()

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

This compiles in Kotlin, why?

1

There are 1 answers

0
Anton Kushch On

Because projected type of arguments will be <Any>. And the test function can be replaced with:

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

To make the function work properly you have to pass the type explicitly:

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

Or if possible specify less generic type:

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