【问题标题】:Creating a list of base class with a list of subclasses使用子类列表创建基类列表
【发布时间】:2014-09-23 01:57:16
【问题描述】:

我有一个基类 (Parent) 的两个子类 (Child1, Child2)。

我有一个包含子类对象的列表 (kids)。我想从kids 创建一个List[Parent] 类型的新列表(typedKids)。

正如您在下面的 REPL 会话中看到的那样,我可以通过将个人元素直接添加到列表 val typedKidsWorks : List[Parent] = List(c1,c2,c3,c4) 来创建一个列表,这是可行的。但是,val typedKids : List[Parent] = List(kids) 没有。知道我在这里缺少什么吗?

scala> abstract class Parent
defined class Parent

scala> case class Child1(name:String) extends Parent
defined class Child1

scala> case class Child2(name:String) extends Parent
defined class Child2

scala> val c1 = Child1("first")
c1: Child1 = Child1(first)

scala> val c2 = Child2("second")
c2: Child2 = Child2(second)

scala> val c3 = Child1("third")
c3: Child1 = Child1(third)

scala> val c4 = Child2("fourth")
c4: Child2 = Child2(four)

scala> val kids = List(c1,c2,c3,c4)
kids: List[Product with Serializable with Parent] = List(Child1(first), Child2(second), Child1(third), Child2(four))

//how to make this work ? 
scala> val typedKids : List[Parent] = List(kids)
<console>:40: error: type mismatch;
 found   : List[Product with Serializable with Parent]
 required: Parent
       val typedKids : List[Parent] = List(kids)

//this works 
scala> val typeKidsWorks : List[Parent] = List(c1,c2,c3,c4)
typeKidsWorks: List[Parent] = List(Child1(first), Child2(second), Child1(third), Child2(four))


                                  ^

【问题讨论】:

    标签: list scala inheritance types


    【解决方案1】:

    kids 已经是List[Parent]。您无需再次致电List。你不需要做任何事情,只需要分配一个任务。

    val typedKids: List[Parent] = kids
    

    或者(虽然没有理由这样做),你也可以写:

    val typedKids: List[Parent] = List(kids:_*)
    

    【讨论】:

      【解决方案2】:

      List(kids) 的类型签名是

      List[List[Product with Serializable with Parent]]
      

      正确的形式是

      val typedKids : List[Parent] = kids
      

      因为kids 已经是Parent 的子类列表

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-01
        • 2021-05-18
        • 2021-04-01
        相关资源
        最近更新 更多