Skip to content

Commit

Permalink
Fix #836 - Update Scala 3 macro for nesting class support
Browse files Browse the repository at this point in the history
  • Loading branch information
cchantep authored and mkurz committed Jan 16, 2024
1 parent b65d173 commit 1b2c379
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,6 @@ object JsMacroImpl { // TODO: debug
val types = tprElements.map(_._2)
val resolve = resolver[Reads, T](forwardExpr, debug)(readsTpe)
val compCls = tpr.typeSymbol.companionClass
val compMod = Ref(tpr.typeSymbol.companionModule)

val (optional, required) = tprElements.zipWithIndex
.map { case ((sym, rpt), i) =>
Expand All @@ -330,7 +329,7 @@ object JsMacroImpl { // TODO: debug
val default: Option[Expr[t]] =
compCls.declaredMethod(f"$$lessinit$$greater$$default$$" + (i + 1)).headOption.collect {
case defaultSym if sym.flags.is(Flags.HasDefault) =>
compMod.select(defaultSym).asExprOf[t]
Ref(tpr.typeSymbol.companionModule).select(defaultSym).asExprOf[t]
}

ReadableField(sym, i, pt, default)
Expand Down
22 changes: 22 additions & 0 deletions play-json/shared/src/test/scala/play/api/libs/json/MacroSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,19 @@ class MacroSpec extends AnyWordSpec with Matchers with org.scalatestplus.scalach

reader.reads(jsPref2).mustEqual(JsSuccess(pref2))
}

"handle nesting class" in {
implicit val textIdFormat: Format[TextId] = Json.valueFormat[TextId]

val nesting = new NestingClass

val expected = nesting.Test(Some(new TextId("foo")))
val expectedJson = Json.obj("underlying" -> "foo")

Json.toJson(expected).mustEqual(expectedJson)

nesting.Test.format.reads(expectedJson).mustEqual(JsSuccess(expected))
}
}
}

Expand Down Expand Up @@ -602,4 +615,13 @@ object MacroSpec {
}

case class Preference[V](key: String, kind: PrefKind.Aux[V], value: V)

class NestingClass {
case class Test(underlying: Option[TextId])

object Test {
implicit def format(implicit textIdFormat: Format[TextId]): Format[Test] =
Json.format[Test]
}
}
}

0 comments on commit 1b2c379

Please sign in to comment.