Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Documentation for custom picklers for unsealed traits #562

Closed
malcolmredheron opened this issue Feb 24, 2024 · 0 comments
Closed

Documentation for custom picklers for unsealed traits #562

malcolmredheron opened this issue Feb 24, 2024 · 0 comments

Comments

@malcolmredheron
Copy link

It took me longer (and more help from chatgpt) than I'd like to figure out a clean way (IMO) of handling unsealed traits and other polymorphic types.

I eventually hit upon this:

      import upickle.default.{macroRW, read, write, ReadWriter as RW, readwriter}

      trait IntOrBool
      case class IntWrapper(i: Int) extends IntOrBool
      case class BoolWrapper(b: Boolean) extends IntOrBool
      given RW[IntWrapper] = macroRW[IntWrapper]
      given RW[BoolWrapper] = macroRW[BoolWrapper]
      given RW[IntOrBool] = readwriter[ujson.Value].bimap[IntOrBool](
        {
          case iw: IntWrapper => writeJs(iw).obj += ("type" -> writeJs("IntWrapper"))
          case bw: BoolWrapper => writeJs(bw).obj += ("type" -> writeJs("BoolWrapper"))
          case t => throw new IllegalArgumentException(s"Unknown type: $t")
        },
        json =>
          json("type").str match {
            case "IntWrapper" => read[IntWrapper](json)
            case "BoolWrapper" => read[BoolWrapper](json)
            case t => throw new IllegalArgumentException(s"Unknown type: $t")
          },
      )

Is there a cleaner way? How would you feel about documenting this or some other approach in the reade?

@com-lihaoyi com-lihaoyi locked and limited conversation to collaborators Jul 11, 2024
@lihaoyi lihaoyi converted this issue into discussion #601 Jul 11, 2024

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant