UPickle and ScalaJS: serialization of sealed features

I am trying to get a basic upickle example to work, and it seems like I'm missing something. I want to try the example provided on the readme page for upickle

import upickle._ sealed trait A @key("Bee") case class B(i: Int) extends A case object C extends A 

Then my code:

 object Model { def main(args: Array[String]): Unit = { val a = B(5): A println(a) val out = write(a) println(out) val a2 = read[A](out) println(a2) println(a == a2) } } 

All I get is an error:

The specified attribute [[A]] has no subclasses. This may occur due to scalac restriction (SI-7046), given that the symptom is not in the same package. If so, the hierarchy can be defined using integer constants.

I have two questions:

  • How can I convince uPickle that the trait is in the same package? (Because it is.)
  • Or if I can’t: how can I define a hierarchy with integer constants?
+8
scala serialization upickle
source share
2 answers

Is there ever a syndrome that you can spend several hours on a problem like this, and you solve it a few minutes after asking the StackOverflow question?

It turns out that, thanks to the details specific to the compiler , such a sealed trait will not know its direct subclasses until there is a point in the file where it is defined. So, in this case, I defined the trait and its cases after the main method, where the upickle will do its macro extension and magic. At the moment, he will not know about cases of signs. If the main method moves in the same file after defining the attribute and its cases, it will work.

+8
source share

I encountered this error in a Scala.js project, where I shared a private abstract class between server and client.

The solution was to use the Typelevel compiler instead of the standard Lightbend.

This is easy to do:

  • Put this in your build.properties : sbt.version=0.13.13-M1
  • and this is at the top of your build.sbt : scalaOrganization in ThisBuild:= "org.typelevel"

For completeness of this class, I can now share between the client and server:

 sealed abstract class ServerResponse case class Ok(msg: String) extends ServerResponse case class Failure(msg: String) extends ServerResponse 
+2
source share

All Articles