3

Consider the following Scala code:

    object MainObject {

    def main(args: Array[String]) {

      import Integer.{
        parseInt => atoi
      }

      println(atoi("5")+2);

      println((args map atoi).foldLeft(0)(_ + _));

  }

First println works fine and outputs 7, but the second one, attempting to map array of strings against a function atoi doesn't work,with error "value atoi is not a member of object java.lang.Integer"

What's the difference?

Illarion Kovalchuk
  • 5,774
  • 8
  • 42
  • 54
  • 1
    Maybe you should add that using `println((args map Integer.parseInt).foldLeft(0)(_ + _))` works to put the emphasis on the import/renaming. – Debilski Sep 06 '10 at 11:57

3 Answers3

5

Looks like a bug. Here's a simpler example.

object A {
  def a(x: Any) = x
  def b = ()
}

{
  A.a(0)
  A.a _
}

{
  import A.a
  a(0)
  a _
}

{
  import A.{a => aa}
  aa(0)
  aa _  //  error: value aa is not a member of object this.A
}

{
  import A.{b => bb}
  bb
  bb _
}
retronym
  • 54,768
  • 12
  • 155
  • 168
4

This is because it can't tell which atoi to use. There are two possibilities parseInt(String) and parseInt(String, int). From the REPL:

scala> atoi <console>:7: error: ambiguous reference to overloaded definition, both method parseInt in object Integer of type (x$1: java.lang.String)Int and  method parseInt in object Integer of type (x$1: java.lang.String,x$2: Int)Int match expected type ?
       atoi

You need to say specifically which one to use, this will work:

println((args map ( atoi(_))).foldLeft(0)(_ + _));
Matthew Farwell
  • 60,889
  • 18
  • 128
  • 171
2

This is not an answer to your question but you could use the toInt method from StringOps instead of Integer.parseInt.

scala> Array("89", "78").map(_.toInt)
res0: Array[Int] = Array(89, 78)
missingfaktor
  • 90,905
  • 62
  • 285
  • 365