代码之家  ›  专栏  ›  技术社区  ›  Illarion Kovalchuk

重命名导入的静态函数有什么问题?

  •  3
  • Illarion Kovalchuk  · 技术社区  · 14 年前

    考虑以下Scala代码:

        object MainObject {
    
        def main(args: Array[String]) {
    
          import Integer.{
            parseInt => atoi
          }
    
          println(atoi("5")+2);
    
          println((args map atoi).foldLeft(0)(_ + _));
    
      }
    

    3 回复  |  直到 14 年前
        1
  •  4
  •   Matthew Farwell    14 年前

    这是因为它不知道该用哪个原子。有两种可能性parseInt(String)和parseInt(String,int)。从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
    

    println((args map ( atoi(_))).foldLeft(0)(_ + _));
    
        2
  •  5
  •   retronym    14 年前

    看起来像个虫子。这里有一个简单的例子。

    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 _
    }
    
        3
  •  2
  •   missingfaktor Kevin Wright    14 年前

    toInt 方法来自 StringOps Integer.parseInt .

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