我写了代码来计算旧式的一些条件。但是有没有其他方法可以使用更多函数式编程编写代码。
def getAgeType(age: Int) =
age match {
case age:Int if (age <= 10) => println("This age belongs to kids")
case age:Int if (age > 10 && age <= 20) => println("This age belongs to teens")
case age:Int if (age > 20 && age <= 60) => println("This age belongs to adults")
case age:Int if (age > 60) => println("This age belongs to adults")
}
有人可以给我更好的代码吗? 提前致谢 康蒂
如果条件变得复杂,您可以使用自定义取消应用模式来使其可读
// ========== Custom unapply pattern ==========
def getAgeType(age: Int): Unit =
age match {
case Kid(_) => println("This age belongs to kids")
case Teen(_) => println("This age belongs to teens")
case Adult(_) => println("This age belongs to adults")
}
object Kid {
def unapply(age: Int): Option[Int] = if (age <= 10) Some(age) else None
}
object Teen {
def unapply(age: Int): Option[Int] = if (age > 10 && age <= 20) Some(age) else None
}
object Adult {
def unapply(age: Int): Option[Int] = if (age > 10) Some(age) else None
}
// ========== Another way ==========
def isKid(age: Int) = age <= 10
def isTeen(age: Int) = age > 10 && age <= 20
def isAdult(age: Int) = age > 20
def getAgeType1(age: Int): Unit =
age match {
case _ if isKid(age) => println("This age belongs to kids")
case _ if isTeen(age) => println("This age belongs to teens")
case _ if isAdult(age) => println("This age belongs to adults")
}
避免这种模式:
age match { case age . . .
case age
代码创建一个与 match 变量同名的新变量,从而隐藏前者并使其在case
子句中不可用。在您的示例中,这不会有太大区别,但它是不必要的,并且使代码看起来很业余。这也是一个坏习惯,在实际代码中看到时会导致真正的混乱。
更好的选择是创建一个指示其用法/含义的新变量。
age match {
case child if child <= 10 => . . .
case old if old > 60 => . . .
或者,更好的是,如果你真的不需要一个新变量。
age match {
case _ if age <= 10 => . . .
case _ if age > 60 => . . .
这使得使用match
对于这个特定的代码来说不是一个很好的"匹配"。
如果您实际上没有检查模式,则应避免使用模式匹配。在您的情况下,您可以使用简单的条件真正简化所有内容:
val category = if (age <= 10) "kids" else if (age <= 20) "teens" else "adults"
println(s"This age belongs to $category")
人们经常忘记,在 Scala 中,表达式实际上是表达式if/else
:它们有一个值,在这种情况下是String
型。这就像其他语言中三元条件的更强大的变体。
在我看来,这比使用模式匹配要简单和简洁得多。它也可能更有效,因为 Scala 编译器经常无法编译与字节码中的有效条件匹配的简单模式。
这个怎么样? 上面的答案给了你很好的建议,但为了可读性,我想建议对你的代码进行一些小的更改。 另请参阅类似问题
//ensure that age is not negative
def getAgeType(age: Int) =
age match {
case _ if 0 to 10 contains age => println("This age belongs to kids")
case _ if 11 to 20 contains age => println("This age belongs to teens")
case _ if 21 to 60 contains age => println("This age belongs to adults")
case _ => println("This age belongs to adults")
}