在match
中使用Scala
合并多个个案时,是否可以给变量赋予引用名称?
代码:
假设Gender
枚举具有三个可能的值,例如male
,female
和other
。
(nameOption, genderOption) match {
case (Some(name), Some(Gender.Male)) | (Some(name), Some(Gender.FeMale))=> s"$name gender is either male or female"
case (None, Some(Gender.Male)) | (None, Some(Gender.FeMale)) => //some print statement
case (Some(name), Some(Gender.Other)) => //some print statement
case _ => //some print statement
}
第一种情况case (Some(name), Some(Gender.Male)) | (Some(name), Some(Gender.FeMale))
是编译器错误,因为在范围内已经定义了 name
。
如果我在实际代码中不合并大小写,则循环复杂性会增加。
答案 0 :(得分:8)
您可以将第一种情况替换为:
case (Some(name), Some(Gender.Male) | Some(Gender.FeMale))=> s"$name gender is either male or female"
更新-更好-感谢@Astrid
case (Some(name), Some(Gender.Male | Gender.FeMale)) => s"$name gender is either male or female"
答案 1 :(得分:7)
您可以尝试以下
(nameOption, genderOption) match {
case (Some(name), Some(gender) if (gender == Gender.Male || gender == Gender.Female) => s"$name gender is either male or female"
}
答案 2 :(得分:6)
除了已经给出的答案之外,如果您发现自己在代码的不同部分重复使用Gender.Male | Gender.FeMale
match子句,则可能需要考虑使用自定义提取器。
object BinaryGender {
def unapply(gender: Gender.Gender) : Option[Gender.Gender] = {
Some(gender).filter(_ != Gender.Other)
}
}
(nameOption, genderOption) match {
case (Some(name), Some(BinaryGender(_))) => s"$name gender is either male or female"
case (None, Some(BinaryGender(_))) => //some print statement
...
}