Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala range returns Long instead of Int

Tags:

types

scala

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?

like image 318
mericano1 Avatar asked Feb 13 '12 12:02

mericano1


1 Answers

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
...
like image 151
ziggystar Avatar answered Oct 15 '22 20:10

ziggystar