5

Hello everybody I'm trying to understand the symbol "_" in scala, it looks like a wildcard but I did not understand why in the given scenario.

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

"_" should act like the variable s, but why it doesn't?

paradigmatic
  • 40,153
  • 18
  • 88
  • 147
Bruno Lee
  • 1,867
  • 16
  • 17
  • I'm about 99.8973% sure that `_` works just fine. It's how you're using it, or what you're expecting of it, that is the issue. – cHao May 21 '13 at 18:54
  • 4
    You should read http://stackoverflow.com/questions/8000903 among other things. You're mixing uses of underscores, I think. (Also, underscore can be used exactly once per variable; a second underscore tries to bind to a second variable, not the first one a second time. So: `foreach{ _ + 1 }` is okay, `foreach{ _ * _ }` is not. If you need to refer to the same variable multiple times, name it: `foreach{ x => x * x }`).) – Rex Kerr May 21 '13 at 19:01

1 Answers1

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.

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228