tabl-6ren">
gpt4 book ai didi

scala - Slick "==="仅编译用于理解

转载 作者:行者123 更新时间:2023-12-02 00:45:51 29 4
gpt4 key购买 nike

我在 slick 中遇到了奇怪的行为,我需要一些帮助来弄清楚为什么会发生这种情况。问题是我有一个查询,内容如下:

db.withSession { implicit session =>
tables.users.where(_.id === UserId(1)).firstOption
}

这不会编译并产生如下错误:

inferred type arguments [Boolean] do not conform to method where's type parameter bounds [T <: scala.slick.lifted.Column[_]]

但是如果我将代码重写为:

db.withSession { implicit session =>
(for {
u <- tables.users if u.id === UserId(1)
} yield u).firstOption
}

它编译并运行良好。

该表定义如下:

class Users(tag: Tag) extends Table[User](tag, "users") {
def id = column[UserId]("id", O.PrimaryKey, O.AutoInc, O.NotNull)
}

我有一个隐式转换来映射 UserId 类型:

implicit lazy val userIdColumnType = MappedColumnType.base[UserId, Int](_.value, UserId(_))

它看起来像是一个类型推断问题,但我无法真正理解为什么会发生它。

有人知道为什么在我报告的两种情况下它的表现会有所不同吗?

编辑:经过一番调查,我发现使用 where 时,userIdColumnType 的隐式转换必须在范围内,而使用 for 理解则不需要。有没有好的解释?

最佳答案

您正在使用 ScalaTest 中的 ===。它返回一个 bool 值。 Slick 的 === 返回一个Column[Boolean]filterwhere 方法阻止使用 bool 值(至少在最新版本的 Slick 中),以防止您意外使用 == 或在您的情况下使用 ScalaTest 的 === ,它对基础值进行本地比较,而不是在数据库中进行相等比较,这才是您真正想要的。 For 推导式被脱糖为 withFilter 并且有时可以生成 bool 值,因此不幸的是我们不能禁止使用 Boolean 推导式。

要解决此问题,您需要确保在查询中选择了 Slick 的 ===。也许您可以通过导入顺序或范围来影响这一点。或者如果你不幸的话你不能并且它们是不兼容的。

我不确定 userIdColumnType 目前如何在这里交互。

关于scala - Slick "==="仅编译用于理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24932736/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com