spray-json and Scala generics

53 views
Skip to first unread message

Maks Atygaev

unread,
Oct 11, 2015, 11:29:11 PM10/11/15
to scala-user
Hello!

I have problem with my generic type.

I have some classes like:

I have trait

trait MyClass[A] {
 
def data: String
}



Also, a few classes:

class SomeClass1 private (val data: String) extends AnyVal with MyClass[SomeClass1]
   
class SomeClass2 private (val data: String) extends AnyVal with MyClass[SomeClass2]



I want to define JsonWriter for MyClass . But I don't understand how to specify the correct definition. I have one simple test:

def f[A <: MyClass[A]](t: MyClass[A]): Unit = {
  println
(toJson(t))
}


But it doesnt compile, because:

Cannot find JsonWriter or JsonFormat type class for my.package.MyClass[A]

I defined json writer:

implicit val myClassWriter = new JsonWriter[MyClass[_]] {
 
override def write(myClass: MyClass[_]): JsValue = {
    myClass
.data.toJson
 
}
}


It looks wrong, but I don't understand how to solve the problem.

monch...@gmail.com

unread,
Oct 30, 2015, 10:03:02 AM10/30/15
to scala-user
I'm having the same problem, did you find a solution in the end?

Jasper-M

unread,
Oct 30, 2015, 10:41:25 AM10/30/15
to scala-user
Hi,

What if you define it like this?

implicit def myClassWriter[T] = new JsonWriter[MyClass[T]] {
 
override def write(myClass: MyClass[T]): JsValue = {
    myClass
.data.toJson
 
}
}

Best,
Jasper

Op maandag 12 oktober 2015 05:29:11 UTC+2 schreef Maks Atygaev:

Jasper-M

unread,
Oct 30, 2015, 10:45:52 AM10/30/15
to scala-user
Or even like this:

implicit def myClassWriter[A <: MyClass[A] = new JsonWriter[A] {
 
override def write(myClass: A): JsValue = {
    myClass
.data.toJson
 
}
}



Op vrijdag 30 oktober 2015 15:41:25 UTC+1 schreef Jasper-M:
Reply all
Reply to author
Forward
0 new messages