Why it compile? int is List<int>, str is List<String>.
fun main() {
val int = listOf(1, 2, 3)
val str = listOf("1")
val result = int.intersect(str)
println(result)
}
Why it compile? int is List<int>, str is List<String>.
fun main() {
val int = listOf(1, 2, 3)
val str = listOf("1")
val result = int.intersect(str)
println(result)
}
intesect
generic parameter T
is deduced as Any
which is an ancestor of both Int
and String
.
It may seem awkward but lists of different types can have non empty intersection:
val l1:List<Number> = listOf(3, 1.2)
val l2:List<Any> = listOf("foo", "bar", 3)
Does this happen frequently? I don’t think so.
Weird. Main question why it deduced to Any. In c# it will be compile error.
val r = listOf(1, "2", 3.0)
Why it shouldn’t? This is a common thing that compiler tries to automatically cast types to their supertypes. See this example:
interface Serializer
object StringSerializer : Serializer
object IntSerializer : Serializer
val serializers = listOf(StringSerializer, IntSerializer) // type: List<Serializer>
I think such code is pretty clear and natural to everyone. It really does the same thing as listOf(1, "2", 3.0)
.
I think the OP has a point here; I don’t think they are worried that the common supertype is computed, but rather that this common supertype happens to be Any
. Implicit cast to Any
is reported in many places, and this looks like just another one of them.