Skip to content

Commit

Permalink
fix: scala 3 default value from fields (#626)
Browse files Browse the repository at this point in the history
  • Loading branch information
liewhite authored Dec 26, 2023
1 parent be55536 commit 3cf1987
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -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]
}

}

0 comments on commit 3cf1987

Please sign in to comment.