【问题标题】:Mapping an ADT to multiple columns in Slick将 ADT 映射到 Slick 中的多个列
【发布时间】:2015-03-25 14:41:48
【问题描述】:

我正在尝试使用 Slick 将 ADT(继承自 sealed trait)的 ADT(case classes)映射为同一个表的多个列,例如:

sealed trait OrValue
case class IntValue(value: Int)
case class StringValue(value: String)

case class Thing(id: Int, value: OrValue)

class Things(tag: Tag) extends Table[Thing](tag, "things") {
  def id = column[Int]("id", O.PrimaryKey)
  def intValue = column[Option[Int]]("intValue")
  def stringValue = column[Option[String]]("stringValue")

  def toThing(_id: String, _intValue: Option[Int], _stringValue: Option[String]): Thing = Thing(id, ((_intValue, _stringValue) match {
    case (Some(a), None) => IntValue(a)
    case (None, Some(a)) => StringValue(a)
  }

  def fromThing(t: Thing): (String, Option[Int], Option[String]) = ??? // elided

  def * = (id, intValue, stringValue) <> ((toThing _).tupled, fromThing)
}

这不符合要求:

[error]  found   : [U]slick.lifted.MappedProjection[Thing,U]
[error]  required: slick.lifted.ProvenShape[Thing]
[error]            ) <> ((toThing _).tupled, fromThing _)

我是不是以错误的方式处理这个问题? 表示 ADT 的惯用方式是什么?

【问题讨论】:

    标签: scala slick


    【解决方案1】:

    问题在于方法toThing和fromThing的签名。

    应该是这样的:

    sealed trait OrValue
    case class IntValue(value: Int)
    case class StringValue(value: String)
    
    case class Thing(id: Int, value: OrValue)
    
    class Things(tag: Tag) extends Table[Thing](tag, "things") {
      def id = column[Int]("id", O.PrimaryKey)
      def intValue = column[Option[Int]]("intValue")
      def stringValue = column[Option[String]]("stringValue")
    
      def toThing(source: (Int, Option[Int], Option[String])): Thing = source match {
        case (id, intValue, stringValue) => ??? //TODO implement
      }
      def fromThing(t: Thing): Option[(Int, Option[Int], Option[String])] = ??? //TODO implement
    
      def * = (id, intValue, stringValue) <> (toThing _, fromThing _)
    }
    

    【讨论】:

      【解决方案2】:

      您不应使用相同的名称命名映射和案例类。例如,将地图类更改为Things。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-22
        • 1970-01-01
        • 1970-01-01
        • 2020-01-11
        • 2016-11-22
        • 2012-09-17
        • 2014-09-03
        相关资源
        最近更新 更多