Scala 我可以按类和变量使用模式匹配吗?

Scala 我可以按类和变量使用模式匹配吗?,scala,pattern-matching,Scala,Pattern Matching,考虑以下示例: def combine(trees: List[CodeTree]): List[CodeTree] = if (trees.isEmpty || singleton(trees)) trees else trees match { case Leaf(cl, wl) :: Leaf(cr, wr) :: tail => Fork(new Leaf(cl, wl), new Leaf(cr, wr), List(cl, cr), wl + wr)

考虑以下示例:

def combine(trees: List[CodeTree]): List[CodeTree] =
  if (trees.isEmpty || singleton(trees)) trees
  else trees match {
    case Leaf(cl, wl) :: Leaf(cr, wr) :: tail =>
      Fork(new Leaf(cl, wl), new Leaf(cr, wr), List(cl, cr), wl + wr) :: tail
  }
我想知道是否可以将两个
Leaf
实例捕获到一个变量中。我希望使用如下语法:

def combine(trees: List[CodeTree]): List[CodeTree] =
  if (trees.isEmpty || singleton(trees)) trees
  else trees match {
    case l: Leaf(cl, wl) :: r: Leaf(cr, wr) :: tail =>
      Fork(l, r, List(cl, cr), wl + wr) :: tail
  }
这实际上并没有编译,但我希望类似的东西


提前谢谢

您使用冒号表示类型,因此必须编写如下内容:

case (l: Leaf[???]) :: (r: Leaf[???]) :: tail =>
但有一种方法可以匹配模式,同时提取模式,即使用“at”符号:


PS:我不知道括号在什么地方是必要的,所以我还是添加了括号。

你用冒号表示类型,所以你必须这样写:

case (l: Leaf[???]) :: (r: Leaf[???]) :: tail =>
但有一种方法可以匹配模式,同时提取模式,即使用“at”符号:


PS:我不知道哪里需要括号,所以我还是添加了括号。

看起来你需要括号,因为var绑定了简单模式或中缀(sp op sp)。是的,括号是必需的。它起作用了!谢谢看起来您需要参数,因为var绑定简单模式或中缀(sp op sp)。是的,括号是必需的。它起作用了!谢谢