Open mikail-khan opened 1 week ago
One solution is to not use Scala's BigDecimal but Java's BigDecimal and then use Schema.primivitve
import zio.*
import zio.json.*
import zio.prelude.{Equal, Validation}
import zio.schema.Schema
import java.math.BigDecimal
object Price {
opaque type Price = BigDecimal
// Factory method with Validation to ensure non-negative Price
def make(amount: BigDecimal): Validation[Chunk[String], Price] =
Validation.fromPredicateWith(Chunk("Price must be non-negative"))(amount)((b: BigDecimal) =>
b.compareTo(BigDecimal.ZERO) >= 0
)
// JSON codec for Price using zio-json, with conversions to handle java.math.BigDecimal
given JsonCodec[Price] = JsonCodec.bigDecimal.transformOrFail(
amount => make(amount).toEither.left.map(_.mkString(", ")), // Handle Chunk errors
price => unwrap(price) // Converts scala.math.BigDecimal to java.math.BigDecimal
)
// Extension method to unwrap the Price back to BigDecimal
extension (price: Price) {
def unwrap: BigDecimal = price
}
// Schema for Price using zio-schema, with validation to ensure non-negative
given Schema[Price] =
Schema
.primitive[BigDecimal]
.transformOrFail(
amount => make(amount).toEither.left.map(_.mkString(", ")), // Handle Chunk errors
price => Right(unwrap(price))
)
// Equality instance for Price using zio.prelude
given Equal[Price] = Equal.default
}
Try to add a implicit Schema of your need as an input for the given, so using Schema[BigDecimal]
on the left hand side
Given the following opaque type:
I receive the following compiler warning:
How do I future proof my code?
I tried to
import zio.schema.Schema.bigDecimal
but it does not get used.I tried to replace the implicit definition as suggested in the warning message to:
but I get: