首页  

scala模式匹配中的@     所属分类 scala 浏览量 654
val l = List(1,2,3)
val s = l match {
  case list @ List(1, _*) => s"a start value is 1 list :$list"
  case list : List[_] => s"a start value not 1 list"
}

list @ List(1, _*) 不能写成 list : List(1, _*)

@ 把 右侧的值绑定到左侧


val f = Future {2/0}
f.onComplete{
 case result @ _ => println(result)
}


f.onComplete{
 case Success(value) => println(value)
 case Failure(error) => println(error)
}



object PatternMatchDemo { def main(args: Array[String]) { val rectangle = Rectangle(2, 3) val circle = Circle(5) val location = Location(7, 9, circle) val group = Group(rectangle, circle, location) info(rectangle) info(circle) info(location) info(group) circle match{ // 匹配项直接赋值给value case value@_ => println(value) } } def info(shape: Shape): Unit = { shape match { // 匹配项直接赋值给v case v@Rectangle(width, height) => println(f"Rectangle ${v}") case v@Circle(r) => println(f"Circle ${v},r=${r}") case v@Location(x, y, shape) => println(f"Location ${v}") // shapes@_* 参数当做数组赋值给变量 shapes case Group(shapes@_*) => shapes.foreach(info) } } abstract class Shape case class Rectangle(width: Int, height: Int) extends Shape case class Circle(radius: Int) extends Shape case class Location(x: Int, y: Int, shape: Shape) extends Shape case class Group(shape: Shape*) extends Shape }

上一篇     下一篇
scala implicit 参数实例

scala运算符 :: :+ +: ::: ++

SBT依赖 % 与 %% 的区别

Scala foldLeft foldRight

play json库简介

akka typed actor 实例之hello