Created
May 14, 2020 14:31
-
-
Save edreyer/0c4b921a55b51e0edb62d00eb283f6e8 to your computer and use it in GitHub Desktop.
ADT basics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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