Reputation: 15552
The following code
fun main(args: Array<String>) {
val a = listOf('A', Pair('X', 'Y'))
println(a[0] == 'B')
}
throws compile errors:
Error:(4, 17) Unresolved reference: ==
Error:(4, 17) No method 'equals(Any?): Boolean' available
Why do these compile errors occur?
EDIT 1: It seems it is not related with a when expression.
EDIT 2: Code snippet (Press the "run" button on the top right to compile)
I need to cast manually to avoid the compile error. Using a smart cast also does not work. (Or val a: List<Any> = listOf('A', Pair('X', 'Y'))
works)
Upvotes: 5
Views: 1813
Reputation: 29844
As it was pointed out in the comments and by Lior Bar-On's answer, the inferred type for val a = listOf('A', Pair('X', 'Y'))
is List<Serializable>
.
The strange thing is that if you let Kotlin infer the type, you cannot compile:
val a = listOf('A', Pair('X', 'Y'))
println(a[0] == 'B')
but if you specify the type explicitely:
val a = listOf<Serializable>('A', Pair('X', 'Y'))
it will. This will not work in the Kotlin playground (try.kotlinlang.org) giving:
Error: Cannot access 'Serializable': it is internal in 'kotlin.io'
but if you compile it locally. This should be filed as bug.
Upvotes: 1
Reputation: 11480
This is a tricky case.
The highest common denominator between Char
and Pair
happen to be the Serializable
interface, which doesn't define an equals()
method. listOf(...)
default type is defined as the highest common denominator of its elements.
Casting the array to List will allow using the equals()
function implemented on Any
, hence let the code work:
fun main(args: Array<String>) {
val a = listOf('A', Pair('X', 'Y')) as List<Any>
println(a[0] == 'B')
println(a[0] == Pair('X', 'Y'))
if (a[0] is Char) {
println(a[0] == 'A')
}
println((a[0] as Char) == 'A')
}
A bit more elegant would be to define the Any
type specifically:
val a = listOf<Any>('A', Pair('X', 'Y'))
Upvotes: 2