2

我有一个简单的案例类:

object Margin {
  def apply(top: Int, right: Int, bottom: Int, left: Int): Margin = {
    Margin(Some(top), Some(right), Some(bottom), Some(left))
  }
}

case class Margin(top: Option[Int], right: Option[Int], bottom: Option[Int], left: Option[Int])

调用upickle.write上述类的实例时,出现以下异常:

scala.ScalaReflectionException: value apply encapsulates multiple     
overloaded alternatives and cannot be treated as a method. Consider 
invoking `<offending symbol>.asTerm.alternatives` and manually picking 
the required method

此错误消息是什么意思,我该如何解决?

4

1 回答 1

1

上述错误消息是Margin类具有多个重载apply方法的结果。第一个是case类构造函数,另一个在伴生对象中。Upickle 不知道apply要使用哪种方法,因此会引发此异常。这是一个已知的限制

一种解决方法是重命名apply伴随对象中的方法。另一种是编写自定义pickler

这是解决问题的自定义pickler的一个有点笨拙的版本:

object Margin {
  def create(top: Int, right: Int, bottom: Int, left: Int): Margin = {
    Margin(Some(top), Some(right), Some(bottom), Some(left))
  }

  implicit val marginWriter = upickle.Writer[Margin]{
    case m =>
      Js.Obj(fields(m).map(kv => (kv._1, Js.Num(kv._2))):_*).asInstanceOf[Js.Value]
  }

  implicit val marginReader = upickle.Reader[Margin]{
    case obj: Js.Obj =>
      val map = obj.value.toMap
      Margin(map.get("top").map(_.value.asInstanceOf[Int]),
        map.get("right").map(_.value.asInstanceOf[Int]),
        map.get("bottom").map(_.value.asInstanceOf[Int]),
        map.get("left").map(_.value.asInstanceOf[Int]))
  }

  private def fields(m: Margin) = Seq(m.top.map(("top", _)), m.right.map(("right", _)), m.bottom.map(("bottom", _)),
    m.left.map(("left", _))).flatten
}
于 2015-06-10T18:44:24.443 回答