7

The toInt method in StringLike doesn't take any arguments, and can only parse in decimal. So to parse binary, hex etc we need to resort to Java's Integer#parseInt(String s, int radix).

In an attempt to remedy this state of affairs, I tried the following

implicit def strToToIntable(s: String) = new {
  def toInt(n: Int) = Integer.parseInt(s, n)
}

However,

"101".toInt(2)

causes the REPL compiler to "crash spectacularly" and doesn't work in compiled code either.

Is there some restriction on overloading existing methods using the "enrich my library" pattern?

0__
  • 66,707
  • 21
  • 171
  • 266
Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180
  • 1
    Are you sure your new tag, ["pimping"](http://en.wikipedia.org/wiki/Pimping), is appropriate? – Blender Oct 27 '11 at 19:32
  • 2
    @tomasz: if I got an upvote for every time I crashed the REPL, I'd have 100000 reputation by now.. – Kim Stebel Oct 27 '11 at 20:05
  • 1
    A compiler crash is never* the result of bad code, only of bad compiler. Or, in other words, the bug is in the compiler. * Well, there's a few exceptions where, though the compiler really shouldn't crash, the code is not correct either. – Daniel C. Sobral Oct 27 '11 at 21:32

2 Answers2

3

Without the implicit, running "101".toInt(2) causes REPL to tell me that Int does not take parameters. So I guess what is happening is that it's running "101".toInt, then trying to call apply(2) on that, which doesn't make sense. I'd suggest a subtle rename of your pimped toInt to avoid the problem.

edit

I just had some success of my own. I explicitly defined a pimped string class as

class StrToRadixInt(s:String) {
  def toInt(radix: Int) = Integer.parseInt(s,radix)
}

implicit def strToToIntable(s:String) = new StrToRadixInt(s)

And REPL was happy:

scala> "101".toInt(2)
res4: Int = 5
Dylan
  • 13,645
  • 3
  • 40
  • 67
  • 4
    It seems that scala does not want to facilitate overloading methods via implicits: see http://stackoverflow.com/questions/4480250/scala-pimp-my-library-with-overloads and http://stackoverflow.com/questions/4443783/overriding-arithmetic-operators-on-int-via-implicit-conversions – Dylan Oct 27 '11 at 21:06
  • The answer is in the links provided above, so accepting this one – Luigi Plinge Oct 28 '11 at 11:40
1

The REPL shouldn't crash--that's a bug. But even so, overloading of names is somewhat discouraged and also not supported in some contexts. Just use a different name:

implicit def parseBase(s: String) = new { def base(b: Int) = Integer.parseInt(s,b) }

scala> "10110" base 2
res1: Int = 22
Rex Kerr
  • 166,841
  • 26
  • 322
  • 407