Home > other >  Scala: Accessing case class defined in another file
Scala: Accessing case class defined in another file

Time:09-23

I have following definitions:

case class MyData(id: String, name: String)

object MyData {
  ....
}

These are in same Scala file.

How can I now access case class in another Scala file? When I try to do something like following in another Scala file:

implicit val dataFormat = jsonFormat2(MyData)

...I get error: Type mismatch, found MyData.type

CodePudding user response:

To elaborate on @jwvh's answer, if you don't define a companion object for a case class, the compiler-generated companion object (part of the case class magic) will express the presence of the apply method in its type, that is to say, for MyData

object MyData extends Function2[String, String, MyData]

This allows the bare companion object to be used in contexts expecting a function, e.g. to Spray's jsonFormat2.

If you define a companion object for the case class yourself, that part of the case class magic is suppressed (though the compiler still generates the apply method unless the case class is abstract), so you can either:

  • Duplicate that bit of compiler magic yourself (see above)
  • Partially-apply the apply call to turn it into a function as in
jsonFormat2(MyData.apply(_, _))
  • Related