I have the following code to print the numbers from 1 to 9 in letters
class IntToNumber(num:Int) {
val digits = Map("1" -> "one", "2" -> "two", "3" -> "three", "4" -> "four", "5" -> "five", "6" -> "six", "7" -> "seven", "8" -> "eight", "9" -> "nine")
def inLetters():String = {
digits.getOrElse(num.toString,"")
}
}
implicit def intWrapper(num:Int) = new IntToNumber(num)
(1 until 10).foreach(n => println(n.inLetters))
When I run this code I get an error saying the method is not available for Long
Script.scala:9: error: value inLetters is not a member of Long
(1 until 10).foreach(n => println(n.inLetters))
^
one error found
Changing the last line to
(1 until 10).foreach(n => println(n.toInt.inLetters))
Works fine..
Can someone help me understand Why is that (1 until 10) range returning Long and not int?
I've changed the name of your implicit conversion to intWrapperX
. The following session shows the fixed example.
The problem is, that your intWrapper
shadows scala.Predef.intWrapper(i:Int): RichInt
which is needed to create the Range
object. I leave the explanation of why the conversion to Long
(or presumable RichLong
) kicks in to the commenters.
scala> :paste
// Entering paste mode (ctrl-D to finish)
class IntToNumber(num:Int) {
val digits = Map("1" -> "one", "2" -> "two", "3" -> "three", "4" -> "four", "5" -> "five", "6" -> "six", "7" -> "seven", "8" -> "eight", "9" -> "nine")
def inLetters():String = {
digits.getOrElse(num.toString,"")
}
}
implicit def intWrapperX(num:Int) = new IntToNumber(num)
// Exiting paste mode, now interpreting.
defined class IntToNumber
intWrapperX: (num: Int)IntToNumber
scala> (1 until 10).foreach(n => println(n.inLetters))
one
two
three
...
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