与我的特征相同类型的列表,但只有实现

List of the same type as my trait, but only with the implementations

假设我有一个名为约束的简单特征:

trait Constraint {

  def description: String

  def constraintValue: Int

  def applyConstraint
}

...和两个扩展此特征的 类:

class ConstraintA(val constraintValue: Int) extends Constraint {

  override def description: String = "CONSTRAINT_A"

  override def applyConstraint: Unit = {
    // ...
  }
}

class ConstraintB(val constraintValue: Int) extends Constraint {

  override def description: String = "CONSTRAINT_B"

  override def applyConstraint: Unit = {
    // ...
  }
}

我正在读取一个 XML 文件并实例化 ConstraintA 和 Constraint B 的列表(具体实现)。

这是我用来读取文件和创建列表的代码:

val xml = XML.loadFile(xmlFilePath)

val readConstraints = (xml \ "constraints") (0).attributes.map {
   c =>
     c.key match {
       case "CONSTRAINT_A" => new ConstraintA(c.value.text.toInt)
       case "CONSTRAINT_B" => new ConstraintB(c.value.text.toInt)
       case _ => Nil
     }
 }

问题是我想 return List[Constraint] 但我收到错误消息:类型 List[Object] 的表达式不符合预期的类型 List[约束].

关于为什么语言不推断类型的任何提示?

谢谢!

实际上,问题是您 return 正在使用两种不同的类型,以防您需要 return 相同的类型(如果您希望编译器推断您的操作类型)。

case "CONSTRAINT_A" => new ConstraintA(c.value.text.toInt)
case "CONSTRAINT_B" => new ConstraintB(c.value.text.toInt)
case _ => Nil

在最后一种情况下,您 returning Nil,即空列表。

在 CONSTRAINT_A 的情况下,您正在 returning CONSTRAINT_A,在 CONSTRAINT_B 的情况下也是如此。这就是编译器将其视为对象列表的原因。

match表达式可以returnConstraintNil,唯一常见的子类型是Any所以结果类型是Any.因此 map 操作 returns List[Any].

解决方法是从匹配表达式中删除 case _

Constraint标记为sealed以避免编译器的投诉