I'm trying to convert a Long into a List[Int] where each item in the list is a single digit of the original Long.
scala> val x: Long = 123412341L
x: Long = 123412341
scala> x.toString.split("").toList
res8: List[String] = List("", 1, 2, 3, 4, 1, 2, 3, 4, 1)
scala> val desired = res8.filterNot(a => a == "")
desired: List[String] = List(1, 2, 3, 4, 1, 2, 3, 4, 1)
Using split("") results in a "" list element that I'd prefer not to have in the first place.
I could simply filter it, but is it possible for me to go from 123412341L to List(1, 2, 3, 4, 1, 2, 3, 4, 1) more cleanly?
If you want the integer values of the digits, it can be done like so:
scala> x.toString.map(_.asDigit).toList
res65: List[Int] = List(1, 2, 3, 4, 1, 2, 3, 4, 1)
Note the difference that the .map(_.asDigit) makes:
scala> x.toString.toList
res67: List[Char] = List(1, 2, 3, 4, 1, 2, 3, 4, 1)
scala> res67.map(_.toInt)
res68: List[Int] = List(49, 50, 51, 52, 49, 50, 51, 52, 49)
x.toString.toList is a List of Chars, i.e. List('1','2','3',...). The toString rendering of the list makes it look the same, but the two are quite different -- a '1' character, for example, has integer value 49. Which you should use depends on whether you want the digit characters or the integers they represent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With