使用 Slick 重构期间类型不匹配

Type mismatch during refactoring using Slick

我有以下一段代码我想制作 DRYer:

def createAdmin(/* ... */): Future[Int] =
  db.run {
    {
      (users returning users.map(_.id)) += Account(0, /* ... */)
    } flatMap { id =>
      admins += Admin(userId = id, /* ... */)
    }
  }

def createStandardUser(/* ... */): Future[Int] =
  db.run {
    {
      (users returning users.map(_.id)) += Account(0, /* ... */)
    } flatMap { id =>
      standardUsers += StandardUser(userId = id, /* ... */)
    }
  }

编译正常。但是,如果我将两者合并为以下内容:

def createUser(role: String)(/* ... */): Future[Int] =
  db.run {
    {
      (users returning users.map(_.id)) += Account(0, /* ... */)
    } flatMap { id =>
      role match {
        case "admin" =>
          admins += Admin(userId = id, /* ... */)
        case "standard" =>
          standardUsers += StandardUser(userId = id, /* ... */)
      }
    }
  }

我收到以下类型不匹配错误:

[error]  found   : Long => slick.dbio.DBIOAction[Int,slick.dbio.NoStream,Nothing]
[error]  required: Long => slick.dbio.DBIOAction[Int,slick.dbio.NoStream,E2]
[error]       } flatMap { id =>
[error]                      ^
[error] one error found

我似乎不明白为什么。有人可以帮我解释一下吗?

恐怕你不能那样重构代码。 我知道从代码的角度来看它看起来很合理。但是 flatMap 中的模式匹配没有为编译器提供足够的信息来推断 effect to the DBIOAction.

正如您在 source code 中看到的那样:

When composing actions, the correct combined effect type will be inferred

所以换句话说,由于Slick在编译时不知道第一次插入后你要做什么,所以编译失败。还有as the documentation says, "it is not possible to fuse this actions for more efficient execution".

编译器无法正确识别使用的效果类型。作为一种解决方法,您应该能够通过指定使用的类型来为其提供一些帮助,例如在 flatMap 操作中,这将是

flatMap[Int, NoStream, Effect.Write] { id => 

你的情况。