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?
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)(_ + _));
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 _
}
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)