我想对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
表示形式?
答案 0 :(得分:2)
来自文档:
class Char:可比较(源)表示16位Unicode 字符。在JVM上,此类型的非空值是 表示为基本类型char的值。
有趣的toLong():长
将此字符的值返回为Long。
使用'4' as Long
时,您实际上会获得字符'4'的Unicode(ASCII)代码
答案 1 :(得分:2)
正如mTak所说,Char代表Unicode值。如果您在JVM上使用Kotlin,则可以按以下方式定义函数:
private fun Long.sumDigits() = this.toString().map(Character::getNumericValue).sum().toLong()
没有理由返回Long
而不是Int
,但我与您的问题相同。
Kotlin的非JVM版本没有Character
类;改用map {it - '0'}
。