Strange compile errors in equality: (No method 'equals(Any?): Boolean' available)

删除回忆录丶 提交于 2019-12-23 03:04:49

问题


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

as in the screenshot:

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)


回答1:


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'))




回答2:


Disclaimer: This answer is based on Kotlin 1.2.71. If you cannot reproduce the described behaviour, please check your Kotlin (plugin) version.

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.



来源:https://stackoverflow.com/questions/53030524/strange-compile-errors-in-equality-no-method-equalsany-boolean-available

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!