diff --git a/tests/shared/src/test/scala/zio/schema/DefaultValueSpec.scala b/tests/shared/src/test/scala/zio/schema/DefaultValueSpec.scala index 8e3cf542b..2bdd13e97 100644 --- a/tests/shared/src/test/scala/zio/schema/DefaultValueSpec.scala +++ b/tests/shared/src/test/scala/zio/schema/DefaultValueSpec.scala @@ -300,6 +300,11 @@ object DefaultValueSpec extends ZIOSpecDefault { val rightSchema = Schema.either(Schema.fail("Nothing"), Schema.primitive(StandardType.StringType)) assert(rightSchema.defaultValue)(isRight(isRight(equalTo("")))) } - ) + ), + suite("default from annotation") { + test("default value from annotation") { + assert(Schema[String].default("default").defaultValue)(isRight(equalTo("default"))) + } + } ) } diff --git a/zio-schema/shared/src/main/scala/zio/schema/Schema.scala b/zio-schema/shared/src/main/scala/zio/schema/Schema.scala index 6b722ce8e..f1432a0e5 100644 --- a/zio-schema/shared/src/main/scala/zio/schema/Schema.scala +++ b/zio-schema/shared/src/main/scala/zio/schema/Schema.scala @@ -57,6 +57,11 @@ sealed trait Schema[A] { */ def defaultValue: scala.util.Either[String, A] + /** + * Add a default value to this schema. + */ + def default(value: A): Schema[A] = self.annotate(fieldDefaultValue(value)) + /** * Chunk of annotations for this schema */ @@ -562,7 +567,15 @@ object Schema extends SchemaPlatformSpecific with SchemaEquality { override def annotate(annotation: Any): Primitive[A] = copy(annotations = (annotations :+ annotation).distinct) - override def defaultValue: scala.util.Either[String, A] = standardType.defaultValue + private def annotatedDefaultValue = annotations.collectFirst { + case a if a.isInstanceOf[fieldDefaultValue[_]] => a.asInstanceOf[fieldDefaultValue[A]].value + } + + override def defaultValue: scala.util.Either[String, A] = + annotatedDefaultValue match { + case Some(value) => Right(value) + case None => standardType.defaultValue + } override def makeAccessors(b: AccessorBuilder): Unit = () }