0
case class Person(name:String,age:Int)

val p1 = Person("Maria",18)

def h(x:Person) = x match{
 case y if y.age >17 => "Adult"
 case z if z.age <=17 => "Younger"  
}

Why in the cases it refers to the age with y or z if the parameter containing the values ​​is x?

1 Answer 1

6

It is because case y means pattern everything and name the variable y, so it is basically creating a new variable that refers to the same object.
However, this is a poor use of pattern matching.

A better alternative would be:

def h(person: Person): String = person match {
  case Person(_, age) if (age > 17) => "Adult"
  case _ => "Younger" // Checking the age here is redudant.
}

Or just use if / else:

def h(person: Person): String =
  if (person.age > 17) "Adult"
  else "Younger"
Sign up to request clarification or add additional context in comments.

2 Comments

I'd disagree that the first alternative is better; changes to Person's definition are a lot more likely to break it.
@AlexeyRomanov Well, some may consider that a good thing, since changes on data model are usually meaningful. But, I do not want to discuss that. With "better" in this case, I meant about the use of pattern matching, because the original code wasn't really pattern matching anything. And for that reason, I also propose the if / else alternative which is shorter and more readable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.