Why does this generic collection fail?


#1

public fun <T> bar(value : Collection<T?>?) { }

public fun test() {
  val foo1 : Set<String?> = HashSet<String?>()
  val foo2 : Set<String?>? = HashSet<String?>()
  val foo3 : Set<String> = HashSet<String>()
  bar(foo1)
  bar(foo2)
  bar(foo3) // Why compile error? Shouldn’t collection with nullable values be able to handle this case automatically?
}


#2

Strictly speaking, it shouldn't: someone to take values out from the set you passed to bar() will be expecting not-null values out of this set. But your bar() may add nulls to the collection.

NOTE: if bar() does not write to the collection, you can specify its parameter as Collection<out T?>, and it will work.