What is wrong with renaming imported static functions?

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

The first println works fine and prints 7, but the second, trying to match an array of strings with the atoi function, does not work, with the error "the value of atoi is not a member of the java.lang.Integer object"

What's the difference?

+3
source share
3 answers

This is because he cannot determine which atoi to use. There are two possibilities parseInt (String) and parseInt (String, int). From 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)(_ + _)); 
+4
source

Looks like a mistake. Here is a simpler example.

 object A { def a(x: Any) = x def b = () } { Aa(0) Aa _ } { import Aa 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 _ } 
+5
source

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

 scala> Array("89", "78").map(_.toInt) res0: Array[Int] = Array(89, 78) 
+2
source

All Articles