From 3cf19870b56f9a30e74856c5437938603e2db71f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E9=9C=96?= Date: Tue, 26 Dec 2023 16:32:57 +0800 Subject: [PATCH] fix: scala 3 default value from fields (#626) --- .../scala-3/zio/schema/DeriveSchema.scala | 6 ++-- .../zio/schema/codec/DefaultValueSpec.scala | 33 +++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 zio-schema-json/shared/src/test/scala-3/zio/schema/codec/DefaultValueSpec.scala diff --git a/zio-schema-derivation/shared/src/main/scala-3/zio/schema/DeriveSchema.scala b/zio-schema-derivation/shared/src/main/scala-3/zio/schema/DeriveSchema.scala index 3b02dc3c3..9c541ddc6 100644 --- a/zio-schema-derivation/shared/src/main/scala-3/zio/schema/DeriveSchema.scala +++ b/zio-schema-derivation/shared/src/main/scala-3/zio/schema/DeriveSchema.scala @@ -278,7 +278,8 @@ private case class DeriveSchema()(using val ctx: Quotes) { } private def defaultValues(from: Symbol): Predef.Map[String, Expr[Any]] = - (1 to from.primaryConstructor.paramSymss.size).toList.map( + val params = from.primaryConstructor.paramSymss.flatten.filter(!_.isTypeParam) + val result = (1 to params.size).toList.map( i => from .companionClass @@ -295,7 +296,8 @@ private case class DeriveSchema()(using val ctx: Quotes) { if (select.isExpr) select.asExpr else select.appliedToType(TypeRepr.of[Any]).asExpr } - ).zip(from.primaryConstructor.paramSymss.flatten.filter(!_.isTypeParam).map(_.name)).collect{ case (Some(expr), name) => name -> expr }.toMap + ).zip(params.map(_.name)) + result.collect{ case (Some(expr), name) => name -> expr }.toMap private def fromConstructor(from: Symbol): scala.collection.Map[String, List[Expr[Any]]] = { val defaults = defaultValues(from) diff --git a/zio-schema-json/shared/src/test/scala-3/zio/schema/codec/DefaultValueSpec.scala b/zio-schema-json/shared/src/test/scala-3/zio/schema/codec/DefaultValueSpec.scala new file mode 100644 index 000000000..cd65b6a00 --- /dev/null +++ b/zio-schema-json/shared/src/test/scala-3/zio/schema/codec/DefaultValueSpec.scala @@ -0,0 +1,33 @@ +package zio.schema.codec + +import zio.Console._ +import zio._ +import zio.json.{ DeriveJsonEncoder, JsonEncoder } +import zio.schema._ +import zio.test.Assertion._ +import zio.test.TestAspect._ +import zio.test.* + +object DefaultValueSpec extends ZIOSpecDefault { + + def spec: Spec[TestEnvironment, Any] = + suite("Custom Spec")( + customSuite, + ) @@ timeout(90.seconds) + + private val customSuite = suite("custom")( + suite("default value schema")( + test("default value at last field") { + val result = JsonCodec.jsonDecoder(Schema[WithDefaultValue]).decodeJson("""{"orderId": 1}""") + assertTrue(result.isRight) + } + ) + ) + + case class WithDefaultValue(orderId:Int, description: String = "desc") + + object WithDefaultValue { + implicit lazy val schema: Schema[WithDefaultValue] = DeriveSchema.gen[WithDefaultValue] + } + +}