While all the above and bellow answers perfectly answer the original question, some additional information can be found in the documentation https://docs.scala-lang.org/tour/pattern-matching.html , they didn't fit in my case but because this stackoverflow answer is the first suggestion in Google I would like to post my answer which is a corner case of the question above.
My question is:
- How to use a guard in match expression with an argument of a
function?
Which can be paraphrased:
- How to use an if statement in match expression with an argument of a
function?
The answer is the code example below:
def drop[A](l: List[A], n: Int): List[A] = l match {
case Nil => sys.error("drop on empty list")
case xs if n <= 0 => xs
case _ :: xs => drop(xs, n-1)
}
link to scala fiddle : https://scalafiddle.io/sf/G37THif/2
as you can see the case xs if n <= 0 => xs
statement is able to use n(argument of a function) with the guard(if) statement.
I hope this helps someone like me.
case x if x.size > 2 => ...
– tstenner