方法类型使用this.type作为类型参数返回对象

时间:2013-11-01 16:51:59

标签: scala types

我有以下记录和DAO:

abstract class SuperRecord
class Record1 extends SuperRecord
class Record2 extends SuperRecord
abstract class SubRecord extends SuperRecord
class SubRecord1 extends SubRecord

abstract class DAO[T <: SuperRecord] extends scala.slick.driver.MySQLDriver.simple.Table[T]
object DAO1 extends DAO[Record1]
object DAO2 extends DAO[Record2]
abstract class SubDAO extends DAO[T <: SubRecord]
object SubDAO1 extends SubDAO[SubRecord1]

然后SuperRecord和Record有以下方法

abstract class SuperRecord {
  def table: DAO[T] forSome {type T <: SuperRecord}
}

class Record1 extends SuperRecord {
  def table = DAO1
}

所有这些都满足了类型检查器。但是,我想在SuperRecord中更改“def table”的签名以指示T IS 记录类型,即在Record1中,表的类型是DAO [Record1]而不是DAO [T :其中SuperRecord],类似

def table: DAO[this.type]

def table: T forSome {type T <: DAO[U forSome {type U <: this.type }]}

两者都不满足类型系统。我想在Scala中完成什么,如果是的话,我应该使用“table”的签名?

1 个答案:

答案 0 :(得分:2)

我认为您可以通过以下方式获得所需的类型特异性级别:

abstract class SuperRecord[T <: SuperRecord[T]] {
  def table: DAO[T]
}
abstract class DAO[T <: SuperRecord[T]] extends Table[T]

允许您定义:

class Record1 extends SuperRecord[Record1] {
  def table = DAO1
}
object DAO1 extends DAO[Record1]