等式中的奇怪编译错误:(无可用的方法“等式(任何?):布尔值") [英] Strange compile errors in equality: (No method 'equals(Any?): Boolean' available)

查看:81
本文介绍了等式中的奇怪编译错误:(无可用的方法“等式(任何?):布尔值")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码

fun main(args: Array<String>) {
    val a = listOf('A', Pair('X', 'Y')) 

    println(a[0] == 'B')
}

引发编译错误:

Error:(4, 17) Unresolved reference: ==
Error:(4, 17) No method 'equals(Any?): Boolean' available

如屏幕截图所示:

为什么会出现这些编译错误?

Why do these compile errors occur?

编辑1 :似乎与when表达式无关.

EDIT 1: It seems it is not related with a when expression.

编辑2 :代码段(按运行"按钮进行编译)
我需要手动进行转换以避免编译错误.使用智能投射也无效. (或者val a: List<Any> = listOf('A', Pair('X', 'Y'))有效)

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)

推荐答案

这是一个棘手的案例.

CharPair之间的最高公分母恰好是Serializable接口,该接口未定义equals()方法. listOf(...)默认类型定义为其元素的最高公分母.

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.

将数组投射到列表将允许使用在Any上实现的equals()函数,因此使代码起作用:

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

更为优雅的是专门定义Any类型:

A bit more elegant would be to define the Any type specifically:

val a = listOf<Any>('A', Pair('X', 'Y'))

这篇关于等式中的奇怪编译错误:(无可用的方法“等式(任何?):布尔值")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆