Reputation: 53994
I wanted to sum the digits of Long
variable and add it to the variable it self, I came with the next working code:
private fun Long.sumDigits(): Long {
var n = this
this.toString().forEach { n += it.toString().toLong() }
return n
}
Usage: assert(48.toLong() == 42.toLong().sumDigits())
I had to use it.toString()
in order to get it work, so I came with the next test and I don't get it's results:
@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())
}
Output:
'4' as Long = 52
"4" as Long = 4
"42" as Long = 42
Is it a good practice to use char.toString().toLong()
or there is a better way to convert char
to Long
?
Does "4"
represented by char
s? Why it is not equal to it char
representation?
Upvotes: 1
Views: 87
Reputation: 11664
As mTak says, Char represents a Unicode value. If you are using Kotlin on the JVM, you can define your function as follows:
private fun Long.sumDigits() = this.toString().map(Character::getNumericValue).sum().toLong()
There's no reason to return Long
rather than Int
, but I've kept it the same as in your question.
Non-JVM versions of Kotlin don't have the Character
class; use map {it - '0'}
instead.
Upvotes: 2
Reputation:
From the documentation:
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.
When you use '4' as Long
you actually get the Unicode (ASCII) code of the char '4'
Upvotes: 2