Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why scala placeholder doesn't work

Tags:

scala

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?

like image 679
Bruno Lee Avatar asked May 21 '13 18:05

Bruno Lee


1 Answers

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.

like image 62
om-nom-nom Avatar answered Nov 08 '22 19:11

om-nom-nom