我正在尝试修改用于 Scala Slick 数据库查询的特征。到目前为止,这是我拥有的两种方法:
protected def findByPrimaryKey(id: PrimaryKeyType): Query[Table[_], T, Seq]
/**
* return the row that corresponds with this record
* @param t - the row to find
* @return query - the sql query to find this record
*/
protected def find(t: T): Query[Table[_], T, Seq]
我想修改这两个方法签名以允许
T
的子类型.例如,如果我有一个记录的特征定义,但需要该特征的具体实现才能实际用于 slick。我试过做这样的事情:/**
* return all rows that have a certain primary key
* @param id
* @return Query object corresponding to the selected rows
*/
protected def findByPrimaryKey(id: PrimaryKeyType): Query[Table[_], _ <: T, Seq]
/**
* return the row that corresponds with this record
* @param t - the row to find
* @return query - the sql query to find this record
*/
protected def find(t: T): Query[Table[_], _ <: T, Seq]
但是我收到如下编译错误:
[error] found : slick.driver.PostgresDriver.simple.Query[slick.driver.PostgresDriver.simple.Table[_],_$8,Seq] where type _$8 <: T
[error] (which expands to) scala.slick.lifted.Query[slick.driver.PostgresDriver.Table[_],_$8,Seq]
[error] required: slick.driver.PostgresDriver.simple.Query[slick.driver.PostgresDriver.simple.Table[_],T,Seq]
[error] (which expands to) scala.slick.lifted.Query[slick.driver.PostgresDriver.Table[_],T,Seq]
[error] Note: _$8 <: T, but class Query is invariant in type U.
[error] You may wish to investigate a wildcard type such as `_ <: T`. (SLS 3.2.10)
[error] val query: Query[Table[_], T, Seq] = find(t)
[error] ^
[error] /home/chris/dev/suredbits-core/src/main/scala/com/suredbits/core/db/CRUDActor.scala:58: type mismatch;
[error] found : slick.driver.PostgresDriver.simple.Query[slick.driver.PostgresDriver.simple.Table[_],_$8,Seq] where type _$8 <: T
[error] (which expands to) scala.slick.lifted.Query[slick.driver.PostgresDriver.Table[_],_$8,Seq]
[error] required: slick.driver.PostgresDriver.simple.Query[slick.driver.PostgresDriver.simple.Table[_],T,Seq]
[error] (which expands to) scala.slick.lifted.Query[slick.driver.PostgresDriver.Table[_],T,Seq]
[error] Note: _$8 <: T, but class Query is invariant in type U.
[error] You may wish to investigate a wildcard type such as `_ <: T`. (SLS 3.2.10)
[error] val query: Query[Table[_], T, Seq] = find(t)
[error] ^
我不确定该怎么做才能得到我想要的结果。
最佳答案
理想情况下,您应该使用 T 制作 Query 变体。但由于这超出了您的控制,您可以这样做(它应该可以工作):
protected def find[U <: T](t: U): Query[Table[_], U, Seq]
但我感觉你在这里处理一个更大的问题。为什么需要这样的抽象?你的类(class)设计是什么?
关于scala - Scala Slick 查询中表格元素的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32104260/