Skip to content

Opaque types with bounds #1272

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

Open
kamilkloch opened this issue Apr 24, 2025 · 1 comment
Open

Opaque types with bounds #1272

kamilkloch opened this issue Apr 24, 2025 · 1 comment

Comments

@kamilkloch
Copy link

In the code below deriving JsonValueCodec[A] ends in a compilation error.
When definition of ReqId is changed to opaque type ReqId = Option[String], derivation succeeds.

object Wrappers {
    opaque type ReqId <: Option[String] = Option[String]

    object ReqId {
      inline def apply(x: Option[String]): ReqId = x

      given JsonValueCodec[ReqId] = JsonCodecMaker.make[Option[String]]
    }
}

object JsoniterOpaque extends App {
  import Wrappers.*

  println(writeToString(ReqId(None))) // null
  println(readFromString[ReqId]("null")) // None
  
  case class A(r: ReqId)

/** Exception occurred while executing macro expansion.
*    java.util.NoSuchElementException: head of empty list
*/
  // given JsonValueCodec[A] = JsonCodecMaker.make 
}
@plokhotnyuk
Copy link
Owner

plokhotnyuk commented Apr 25, 2025

Hi, Kamil!

Thanks for reporting an issue!

Opaque types are not supported yet and I suppose that a custom codec for ReqId cannot be summoned due to a known bug in the Scala 3 compiler: scala/scala3#21199

There are several examples in tests where custom codec for opaque type works fine:
https://github.com/plokhotnyuk/jsoniter-scala/tree/master/jsoniter-scala-macros/shared/src/test/scala-3/com/github/plokhotnyuk/jsoniter_scala/macros

Probably opaque type ReqId = Option[String] works only because TypeRepr.dealias converts it into Option[String].

In v2.35.2 release I've added a proper message for the compilation failure instead of java.util.NoSuchElementException: head of empty list.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants