tags:

views:

113

answers:

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?

+5  A: 

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
+4  A: 

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)(_ + _));
MatthieuF
I don't think that's a problem. http://pastebin.com/Ac6FKD2b
missingfaktor
And why does `println((args map Integer.parseInt).foldLeft(0)(_ + _))` work without problems?
Debilski
It works. (atoi(_)) is the solution
Shaman
+2  A: 

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