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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With