Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Fix Ambiguous Reference to Overloaded apply() method when deserializing Json

Given the following case class that needs to be serialized/deserialized to/from JSON...

import play.api.libs.json
import play.api.libs.functional.syntax._

trait MyTrait(s1: String, s2: String)

case class MyClass(s1: String, s2: String) extends MyTrait {

  def this(t: MyTrait) = this(t.s1, t.s2)
}

object MyClass {

  def apply(t: MyTrait) = new MyClass(t)

  implicit val myClassJsonWrite = new Writes[MyClass] {
    def writes(c: MyClass): JsValue = {
      Json.obj(
        "s1" -> c.s1,
        "s2" -> c.s2
      )
    }
  }

  implicit val myClassJsonRead = (
    (__ \ 's1).read[String] ~
    (__ \ 's2).read[String]
  )(MyClass.apply _)
}

... I always get the following error message:

[error] /home/j3d/Projects/test/app/models/MyClass.scala:52: ambiguous reference to overloaded definition,
[error] both method apply in object MyClass of type (s1: String, s2: String)models.MyClass
[error] and  method apply in object MyClass of type (t: MyTrait)models.MyClass
[error] match expected type ?
[error]   )(MyClass.apply _)
[error]             ^

... why doesn't the compiler infer the right apply method? How could I fix this error? Any help would be really appreciated. Thanks.

like image 477
j3d Avatar asked Feb 24 '13 15:02

j3d


1 Answers

You can select the correct method like this:

MyClass.apply(_: String, _: String)

The compiler can not infer the correct type because you reference the apply method. Because you explicitly reference them the compiler will not make that choice for you.

To make the syntax a bit more readable you can change you companion object definition

object MyClass extends ((String, String) => MyClass) {

That way you can simply reference the companion object instead of the ambiguous apply method

implicit val myClassJsonRead = (
  (__ \ 's1).read[String] ~
  (__ \ 's2).read[String])(MyClass)
like image 180
EECOLOR Avatar answered Oct 29 '22 17:10

EECOLOR