Scala 带有子类条目的模式匹配列表

Scala 带有子类条目的模式匹配列表,scala,map,polymorphism,pattern-matching,Scala,Map,Polymorphism,Pattern Matching,我创建了一个抽象基类,如下所示: abstract class parent 然后,我继续创建了两个从父类继承的case类: case class child1(name:String,category:String) extends parent case class child2(name:String,category1:String,category2:String) extends parent 然后,对于kicks,我创建了一个类型为parent的列表,并将child1和chi

我创建了一个抽象基类,如下所示:

abstract class parent
然后,我继续创建了两个从父类继承的case类:

case class child1(name:String,category:String) extends parent

case class child2(name:String,category1:String,category2:String) extends parent
然后,对于kicks,我创建了一个类型为parent的列表,并将child1和child2追加到其中:

val childList = List[parent]()

scala> child1("Child","One") :: child2("Child","Two","dhshs")::childList
res2: List[parent] = List(child1(Child,One), child2(Child,Two,dhshs))
到目前为止,列表[Parent]中有两个子类型

现在,我想遍历这个列表,并根据子对象的基本类型,对该特定类型执行一些特殊的操作。所以我这样做:

scala> res2 map {case child1 => "Child1";case child2 => "Child2"}
我希望看到一个
列表[String](“Child1”、“Child2”)
,但我得到了以下结果:

<console>:15: error: unreachable code
              res2 map {case child1 => "Child1";case child2 => "Child2"}
scala> res2 map {r => r match {case child1 => "Child1"}}
res8: List[java.lang.String] = List(Child1, Child1)

scala> res2 map {case child1 => "Child1"}
res9: List[java.lang.String] = List(Child1, Child1)
正如你所看到的,我得到了“Child1”作为我的列表条目,即使是“child2”,我也得到了Child1


非常困惑,有人能告诉我这是怎么回事吗?

问题就在这里:child1和child2是为保存结果而创建的新变量

res2 map {case child1 => "Child1";case child2 => "Child2"}
试试这个:

res2 map {case x:child1 => "Child1";case y:child2 => "Child2"}

x
y
分别是关联类型为
child1
child2
的变量。

问题在于:child1和child2是为保存结果而创建的新变量

res2 map {case child1 => "Child1";case child2 => "Child2"}
试试这个:

res2 map {case x:child1 => "Child1";case y:child2 => "Child2"}

x
y
分别是关联类型为
child1
child2
的变量。

为了澄清,当您仅创建模式变量时,无论是
child1
还是
child2
,您根本没有约束这些模式变量(它们允许的绑定)。因此,第一个绑定到任何值(即类型为
any
!)的值),因此第二个
case
子句无法匹配。如Korefn所示,通过使用
case name:Type=>
符号,您可以区分类
child1
child2
。最后,
trait
s、
class
es(包括
abstract class
es)和
object
s的名称应以大写字母开头。此外,您还可以使用
`child1`
`child2`
(带记号)@indonnie
case.\uquo:'child1'
带有记号会为
map
foreach
抛出匹配错误,除非使用
collect
@Randall说得很好。澄清一下,当您仅仅创建一个模式变量时,无论是
child1
还是
child2
,您根本没有约束这些模式变量(它们允许的绑定)。因此,第一个绑定到任何值(即类型为
any
!)的值),因此第二个
case
子句无法匹配。如Korefn所示,通过使用
case name:Type=>
符号,您可以区分类
child1
child2
。最后,
trait
s、
class
es(包括
abstract class
es)和
object
s的名称应以大写字母开头。此外,您还可以使用
`child1`
`child2`
(带记号)@indonnie
case.\uquo:'child1'
带有记号会为
map
foreach
抛出匹配错误,除非使用
collect
@兰德尔说得很好。