Scala语言作为一个整体函数的用法
示例
部分功能在惯用的Scala中非常常见。它们通常case基于其方便的语法而使用,以定义特征上的全部功能:
sealed trait SuperType //“sealed”修饰符仅允许在当前构建单元内进行继承
case object A extends SuperType
case object B extends SuperType
case object C extends SuperType
val input: Seq[SuperType] = Seq(A, B, C)
input.map {
case A => 5
case _ => 10
} //序列(5,10,10)这样可以将match语句的其他语法保存在常规匿名函数中。比较:
input.map { item =>
item match {
case A => 5
case _ => 10
}
} //序列(5,10,10)当元组或案例类传递给函数时,它也常用于通过模式匹配执行参数分解:
val input = Seq("A" -> 1, "B" -> 2, "C" -> 3)
input.map { case (a, i) =>
a + i.toString
} // Seq("A1", "B2", "C3")