scala模式匹配错误java.lang.NoSuchMethodError:scala.collection.immutable.$colon$colon.hd$1()Ljava/lang/Object;
我编写了以下代码:scala模式匹配错误java.lang.NoSuchMethodError:scala.collection.immutable.$colon$colon.hd$1()Ljava/lang/Object;,scala,pattern-matching,runtime-error,Scala,Pattern Matching,Runtime Error,我编写了以下代码: def combine(trees: List[CodeTree]): List[CodeTree] = { if (trees.length >= 2) makeCodeTree(trees.head, trees.tail.head) :: trees.tail.tail else trees } 它给出了以下结果(我所期望的): 我的代码的问题是它看起来不好看 因此,我决定将其重构为(使用模式匹配): 我希望得到与前面代码示例相同的结果 但我不明
def combine(trees: List[CodeTree]): List[CodeTree] = {
if (trees.length >= 2) makeCodeTree(trees.head, trees.tail.head) :: trees.tail.tail
else trees
}
它给出了以下结果(我所期望的):
我的代码的问题是它看起来不好看因此,我决定将其重构为(使用模式匹配):
我希望得到与前面代码示例相同的结果 但我不明白为什么我在Scala工作表中出现这个错误(NoSuchMethodError)。我怎么修理它 请注意,下面的代码适用于模式匹配,但是(如图所示)我得到了一个错误的答案
def combine(trees: List[CodeTree]): List[CodeTree] = trees match {
case t1 :: t2 :: ts => ts
case _ => trees
}
如果CodeTree不是case类,则需要使用apply和unapply方法创建一个伴随对象。使用case类,您可以在后台免费获得这些方法,它们是模式匹配所必需的。如果我将
CodeTree
替换为String
,则您的代码没有任何问题
def combine(trees: List[CodeTree]) : List[CodeTree] = trees match {
case t1 :: t2 :: ts => makeCodeTree(t1,t2) :: ts
case _ => trees
}
def combine(trees: List[CodeTree]): List[CodeTree] = trees match {
case t1 :: t2 :: ts => ts
case _ => trees
}