【发布时间】:2019-09-10 04:37:40
【问题描述】:
我有这两个特点:
sealed trait DbValue {
type R
type T <: DbValue
def content(): R
def copy(newContent: R = content): Option[T]
def toString(): String
}
sealed trait DbValueOps {
type R
type T <: DbValue
def apply(newContent: R): Option[T]
def fromString(newContent: String): Option[T]
def isValidContent(newContent: R): Boolean
}
并且想要创建一个方法/类来获取实现这两个特征的对象,但是,DbValue 由类实现,而 DbValueOps 由伴随对象实现。
例子:
case class Column[T <: DbValue with DbValueOps] (val name: String, val cells: Vector[Option[T]] = Vector(), val blank_allowed: Boolean = true) {}
我现在想在这样实现的类型上创建一个通用的列:
case class DbString private (val content: String) extends DbValue {
type R = String
type T = DbString
def copy(newContent: String = content): Option[DbString] = DbString(newContent)
override def toString(): String = content
}
object DbString extends DbValueOps {
type R = String
type T = DbString
def apply(newContent: String): Option[DbString] =
isValidContent(newContent) match {
case true => Some(new DbString(newContent))
case false => None
}
def fromString(newContent: String): Option[DbString] = DbString(newContent)
def isValidContent(newContent: String): Boolean = !newContent.isEmpty
}
但是,当我尝试制作这样的专栏时,使用:Column[DbString]("name")
我得到错误:type arguments [database.DbString] do not conform to method apply's type parameter bounds [T <: database.DbValue with database.DbValueOps]
有什么好办法吗?或者我应该如何改变我的设计?
【问题讨论】:
标签: scala generics polymorphism traits companion-object