Kotlin 中两个字符的总和

Sum of two chars in Kotlin

我正在学习 Kotlin,我想知道为什么我可以在 Kotlin 中的两个 Char 变量之间进行减法,但它们的总和会出现此错误:

    >>> 'A' + 'B'
error: the character literal does not conform to the expected type Int
'A' + 'B'
      ^

>>> 'A' - 'B'
res40: kotlin.Int = -1
>>>

我知道这是一个非常基本的问题...

谢谢!

根据 documentation,如果仅依靠 Kotlin 的类型推断完成操作,这是不可能的。 'A' + 'B'可以写成'A'.plus('B'),但是Char的加法运算符(.plus)在第二个包裹里只接受Int。

使这个操作起作用的一种方法是 'A' + 'B'.toInt(),但它仍然不会打印合法答案,因为值的总和 'A' = 65 和 'B' = 66 在 ASCII table.

中不存在