I’m really missing a useful function in Kotlin. Right now the only way to convert an Int to a List of Digits (Int) is to create a method or use toString which is rather ugly.
Could you provide a function for the Int class which converts a number to its digits via modulo 10 and dividing by 10?
fun Int.toDigits(): List<Int> = toString().map { it.toString().toInt() }
Unfortunately this is as close as you can really get. That’s why you write your own extension methods for it. You only have to write the ugly once and you can write it your nice way every other time! The joy of programming.
I guess the fact that you need to call toString().toInt() instead of calling toInt() directly is a bit annoying, but you only have to write this once so I don’t care.
A version that doesn’t return an empty list with 0 as an input
fun Int.toDigits(base: Int = 10): List<Int> = sequence {
var n = this@toDigits
require(n >= 0)
if (n == 0) yield(n)
while (n != 0) {
yield(n % base)
n /= base
}
}.toList()