【问题标题】:Scala List with only subclasses只有子类的 Scala 列表
【发布时间】:2013-08-18 04:56:16
【问题描述】:

有没有办法拥有 List["only subclasses of DataElement"] 或 List["only with trait Element"]?

我以为会是这样的

val test: List[_ <: DataElement] = List(DataElement("hi"), DataMessage("ho"))

DataMessage extends DataElement

但我得到了这个错误

type mismatch; found : DataMessage.type required: DataElement

【问题讨论】:

    标签: list scala seq subclass


    【解决方案1】:

    为我工作:

    trait Element
    class DataElement(s: String) extends Element
    class DataMessage(s: String) extends DataElement(s)
    
    val test: List[_ <: DataElement] = List(new DataElement("hi"), new DataMessage("ho"))
    println(test) // List(Test$DataElement$1@13c695a6, Test$DataMessage$1@17386918)
    

    但您不需要_ &lt;: 语法。这些更好:

    val test: List[DataElement] = List(new DataElement("hi"), new DataMessage("ho"))
    val test: List[Element] = List(new DataElement("hi"), new DataMessage("ho"))
    

    【讨论】:

    • 感谢您的快速响应,我的问题是由于类的伴随对象。
    • 也许您应该编辑您的问题以使其具有上下文?很难猜出你的意思。
    【解决方案2】:

    你有点把事情复杂化了。你可以这样做:

    val test: List[DataElement] = List(DataElement("hi"), DataMessage("ho"))
    

    【讨论】:

    • 感谢您的快速响应,我的问题是由于类的伴随对象。
    猜你喜欢
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 2013-04-04
    • 2011-09-02
    • 2021-08-20
    相关资源
    最近更新 更多