kotlin - 为什么将单个char和 “single char String”转换为long(.toLong())时不相等

标签 kotlin tostring long-integer

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

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)代码

关于kotlin - 为什么将单个char和 “single char String”转换为long(.toLong())时不相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51582890/

相关文章:

c++ - static_assert'ion long 和 int 是同一类型

javascript - 如何在 JavaScript 中将长日期值转换为字符串格式

kotlin - 启用 proguard 后无法访问 kotlin 类中使用的伴随对象

java - 打印 JAXB 生成的 bean

java - MongoDB group() 函数中使用 Long 累加器代替 Double

c# - 强制 Visual Studio 调试工具显示有用的信息

C# 调试 : [DebuggerDisplay] or ToString()?

kotlin - ktor sslConnector 从 jar p12 pkcs12 jks keystore 和 mtls 相互 ssl 连接中服务/读取

kotlin - 重组后如何保持对元素的关注?

kotlin - 使用一些常量和其他变量创建一个构建器