简体   繁体   English

scala中的函数如何匹配?

[英]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?为什么在这些情况下,如果包含值的参数是 x,它用 y 或 z 表示年龄?

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.这是因为case y意味着模式化一切并命名变量y ,所以它基本上是创建一个引用同一个对象的新变量。
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 :或者只使用if / else

def h(person: Person): String =
  if (person.age > 17) "Adult"
  else "Younger"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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