5

大家好,我试图理解 scala 中的符号“_”,它看起来像一个通配符,但在给定的场景中我不明白为什么。

   var l = List("a","b" ,"c")
   // Works "s" works as a variable.
   l.foreach( s =>
     if(s=="a"){
       print(s)
     }
   )

   // Works _ takes the place of "s"
   l.foreach(
     print(_)
   )

  //So the doubt is whether "_" is a wildcard that does not work well.

  l.foreach(
    if(_=="a"){
      print(_)
    }
  )

"_" 应该像变量一样s,但为什么不呢?

4

1 回答 1

12

Wildcards in anonymous functions are expanded in a way that n-th _ is treated as n-th argument. The way you're using it makes scala compiler think you're actually have something like

l.foreach((x,y) =>
    if(x=="a"){
      print(y)
    }
)

Which is obviously invalid.

于 2013-05-21T19:03:55.473 回答