我需要能够通过在某些情况下提供除 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/

    10-16 02:35