为什么单个 char 和 "single char String" 在转换为 long (.toLong()) 时不相等

Why single char and "single char String" not equal when converted to long (.toLong())

我想对 Long 变量的数字求和并将其添加到它自己的变量中,我带来了下一个 working 代码:

private fun Long.sumDigits(): Long {
    var n = this
    this.toString().forEach { n += it.toString().toLong() }
    return n
}

用法:assert(48.toLong() == 42.toLong().sumDigits())

我必须使用 it.toString() 才能让它工作,所以我进行了下一个测试,但我没有得到它的结果:

@Test
fun toLongEquality() {
    println("'4' as Long = " + '4'.toLong())
    println("\"4\" as Long = " + "4".toLong())
    println("\"42\" as Long = " + "42".toLong())

    assert('4'.toString().toLong() == 4.toLong())
}

输出:

'4' as Long = 52
"4" as Long = 4
"42" as Long = 42

使用 char.toString().toLong() 是一个好习惯还是有更好的方法将 char 转换为 Long

"4"是否代表char?为什么它不等于char表示呢?

来自文档:

class Char : Comparable (source) Represents a 16-bit Unicode character. On the JVM, non-nullable values of this type are represented as values of the primitive type char.

fun toLong(): Long

Returns the value of this character as a Long.


当您使用 '4' as Long 时,您实际上得到了字符“4”的 Unicode (ASCII) 代码

正如mTak所说,Char代表一个Unicode值。如果你在 JVM 上使用 Kotlin,你可以这样定义你的函数:

private fun Long.sumDigits() = this.toString().map(Character::getNumericValue).sum().toLong()

没有理由 return Long 而不是 Int,但我已将其与您的问题保持一致。

Kotlin 的非 JVM 版本没有 Character class;请改用 map {it - '0'}