简体   繁体   中英

How function match in scala?

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?

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM