Skip to content
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

fix: scala 3 default value from fields #626

Merged
merged 1 commit into from
Dec 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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]
}

}
Loading