Scala使用静态方法从类继承

时间:2016-04-14 00:00:30

标签: scala inheritance polymorphism

我有一个我希望扩展的抽象类SQLTuple:

abstract class SQLTuple() {
    val attributes : List[FieldName[_]]
}

例如,StudentsSQLTuple

的子类
class Student() extends SQLTuple {
    val id = Field[Int]("id")
    val name = Field[String]("name")
    val age = Field[Int]("age")

    override val attributes = List(id, name, age)
}

我还有另一个函数,它接受SQLTupleSQLTuple的子类,并且根据类,我希望得到它attributes

def apply[A <% SQLTuple](table_name : String) = {
    val attributes = A.attributes
    new SQLSet[A](Relation(table_name, attributes))
}

我知道这不起作用,因为属性不是静态字段。如果我想创建一个,我可以为SQLTuple类创建一个伴随对象。但是,我无法弄清楚如何强制SQLTuple的子类继承伴随对象中定义的任何静态方法。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:1)

你可以使用implicits做这样的事情:

case class Attributes[A](value: List[FieldName[_]])

abstract class SQLTuple[A](implicit val attributes: Attributes[A])

class Student() extends SQLTuple[Student] 

object Student {
  val id = Field[Int]("id")
  val name = Field[String]("name")
  val age = Field[Int]("age")
  implicit val studentAttrs = Attributes[Student](List(id, name, age))
}

def apply[A <: SQLTuple[A]](table_name: String)(implicit attributes: Attributes[A]) = {
  val attributes = attributes.value
  new SQLSet[A](Relation(table_name, attributes))
}

答案 1 :(得分:0)

如评论中所述,Scala没有静态值。但通过查看您的示例,您似乎甚至不想要静态值。在

abstract class SQLTuple() {
    val attributes : List[FieldName[_]]
}

val attributes抽象val 。因此,需要为SQLTuple的每个直接子类定义它。最简单的解决方案是:

def apply[A <: SQLTuple](table_name : String, sql_tuple: A) = {
    val attributes = sql_tuple.attributes
    new SQLSet[A](Relation(table_name, attributes))
}