I am being puzzled by some aspects of type and nullability inference of Pairs.
Given these classes and enums
class Foo
class Bar
enum class Baz { BAZ }
enum class Qux { QUX }
val foos: List<Foo> = listOf(Foo())
val bars: List<Bar> = listOf(Bar())
These expressions do not compile — as one would expect:
Pair(1, Foo()) == Pair(Foo(), 1) // does not compile
Pair(Foo(), Bar()) == Pair(Bar(), Foo()) // does not compile
Pair(1, "string") == Pair("string", 1) // does not compile
Pair(1L, 1) == Pair(1, 1L) // does not compile
But on the other hand, if I use lists or enums, the compiler accepts these:
Pair(foos, bars) == Pair(bars, foos) // compiles
Pair(1, foos) == Pair(foos, 2) // compiles
Pair(Baz.BAZ, Qux.QUX) == Pair(Qux.QUX, Baz.BAZ) // compiles
The nullability also confuses me:
val list: List<Pair<String, Int?>> = listOf("foo" to 1, "bar" to null)
val filtered: List<Pair<String, Int>> = list.filterIsInstance<Pair<String, Int>>()
assert(filtered.size == 2) // why‽
Why does filterIsInstance
not filter the second item out?
Can someone explain what’s going on?