scala - `apply` 方法重载时 : Slick error message 'value tupled is not a member of object'

标签 scala slick

我需要能够通过在某些情况下提供除 User 之外的所有值来创建 id 对象,以便 User 对象负责为自己分配一个自动生成的值。

为此,我重载了伴生对象中的 apply 方法,如下所示。但这会导致编译时错误: value tupled is not a member of object

StackOverflow 和其他博客上提到的解决方案不起作用,例如:
http://queirozf.com/entries/slick-error-message-value-tupled-is-not-a-member-of-object

case class User(id: Long, firstName: String, lastName: String, mobile: Long, email: String)

object User {
  private val seq = new AtomicLong

  def apply(firstName: String, lastName: String, mobile: Long, email: String): User = {
    User(seq.incrementAndGet(), firstName, lastName, mobile, email)
  }
}

class UserTableDef(tag: Tag) extends Table[User](tag, "user") {

  def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
  def firstName = column[String]("first_name")
  def lastName = column[String]("last_name")
  def mobile = column[Long]("mobile")
  def email = column[String]("email")

  override def * =
    (id, firstName, lastName, mobile, email) <> (User.tupled, User.unapply)

}

最佳答案

你的问题的根源是重载的 apply def。
tupled 不适用于带有 case classless than 2 parametersoverloaded apply

就 slick 的 *(或全部)映射和 <> 而言,它应该是这样的,

def * = (tupleMember1, tupleMember2, ...) <> (func1, func2)

这样,
  • func1 将该元组 (tupleMember1, tupleMember2, ...) 作为输入并返回映射类/案例类的实例。
  • func1 获取映射类/案例类的实例并返回该元组 (tupleMember1, tupleMember2, ...)

  • 所以你可以提供任何功能......满足这些要求。
    case class User(id: Long, firstName: String, lastName: String, mobile: Long, email: String)
    
    object User {
      private val seq = new AtomicLong
    
      def apply(firstName: String, lastName: String, mobile: Long, email: String): User = {
        User(seq.incrementAndGet(), firstName, lastName, mobile, email)
      }
    
      def mapperTo(
        id: Long, firstName: String,
        lastName: String, mobile: Long, email: String
      ) = apply(id, firstName, lastName, mobile, email)
    
    }
    
    class UserTableDef(tag: Tag) extends Table[User](tag, "user") {
    
      def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
      def firstName = column[String]("first_name")
      def lastName = column[String]("last_name")
      def mobile = column[Long]("mobile")
      def email = column[String]("email")
    
      override def * =
        (id, firstName, lastName, mobile, email) <> ((User.mapperTo _).tupled, User.unapply)
    
    }
    

    关于scala - `apply` 方法重载时 : Slick error message 'value tupled is not a member of object' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41179532/

    相关文章:

    Scala扩展while循环到do-until表达式

    scala - 如何使用 Slick Lifted Embedding 更新多列?

    postgresql - 使用 Slick 进行多重 OR 过滤

    postgresql - 由于含糊不清的隐式,无法将 MappedProjection 转换为 ProvenShape

    scala - 使用 scala-parser-combinators 的递归定义

    scala - Spark SQL 不支持 JSONPATH 通配符的任何解决方法

    Option[String] 情况下的 Scala 大小写模式匹配错误

    scala - 为什么 += 不适用于列表?

    database - 在 Slick 3 的事务中执行非数据库操作

    scala - 将自定义谓词传递给 TableQuery 的过滤方法