Skip to content

Instantly share code, notes, and snippets.

@edreyer
Created May 14, 2020 14:31
Show Gist options
  • Save edreyer/0c4b921a55b51e0edb62d00eb283f6e8 to your computer and use it in GitHub Desktop.
Save edreyer/0c4b921a55b51e0edb62d00eb283f6e8 to your computer and use it in GitHub Desktop.
ADT basics
sealed trait Quantity
object Quantity {
final case class UnitQuantity private (units: Int) extends Quantity
final case class WeightQuantity private (kgs: Double) extends Quantity
// factory with validation
object UnitQuantity {
def create(units: Int): Either<ValidationError, UnitQuantity> =
if (units <= 0) Either.left(ValidationError("units must be positive"))
else Either.right(UnitQuantity(units))
}
// factory with validation
object WeightQuantity {
def create(units: Int): Either<ValidationError, WeightQuantity> =
if (units <= 0.0) Either.left(ValidationError("kgs must be positive"))
else Either.right(UnitQuantity(units))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment