Integration with Circe (JSON encoding/decoding)
Importing the Circe integration:
// For Circe version 0.14.x
libraryDependencies += "io.monix" %% "newtypes-circe-v0-14" % "0.3.0"
Usage:
import monix.newtypes._
import monix.newtypes.integrations.DerivedCirceCodec
type Email = Email.Type
object Email extends NewtypeValidated[String] with DerivedCirceCodec {
def apply(v: String): Either[BuildFailure[Type], Type] =
if (v.contains("@"))
Right(unsafeCoerce(v))
else
Left(BuildFailure("missing @"))
}
You can now serialize and deserialize to/from JSON:
import io.circe.syntax._
import io.circe.parser.decode
decode[Email](
Email.unsafe("[email protected]")
.asJson
.noSpaces
)
// res0: Either[io.circe.Error, Email] = Right(value = "[email protected]")
decode[Email](
Email.unsafe("la, la, lalalala")
.asJson
.noSpaces
)
// res1: Either[io.circe.Error, Email] = Left(
// value = DecodingFailure at : Invalid Email — missing @
// )