【问题标题】:Subtype for a table element in a Scala Slick QueryScala Slick Query 中表元素的子类型
【发布时间】:2015-08-19 19:40:19
【问题描述】:

我正在尝试修改用于 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]                                                  ^

我不确定如何才能获得我想要的结果。

【问题讨论】:

    标签: scala slick


    【解决方案1】:

    理想情况下,您应该使用 T 来制作 Query 变体。但由于这是您无法控制的,您可以这样做(应该可以):

    protected def find[U <: T](t: U): Query[Table[_], U, Seq]
    

    但我感觉你正在处理一个更大的问题。为什么需要这样的抽象?你的班级设计是什么?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-20
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多