Search code examples
genericskotlinkotlin-null-safety

Method call with nullable and not nullable Collection


Is it possible in Kotlin to write a function which can be called with nullable and not nullable collections? I think about something like this:

fun <C: MutableCollection<out String>> f(c: C): C {
    // ...
}

Not that I need to write it like this because I have a return value of type C. Also note the out keyword but even with it I can't call f(mutableListOf<String?>) but f(mutableListOf<String>) works fine. What do I have to change here or isn't that possible in Kotlin? With arrays this would work just fine...


Solution

  • fun <C: MutableCollection<out String?>> f(c: C): C {
        return c;
    }
    
    fun main(args: Array<String>) {
        println(f(mutableListOf("hello")))
        println(f(mutableListOf<String?>(null)))
    }