Created
July 23, 2020 15:26
-
-
Save debasishg/0ab6bdf5e4bc8d4a1f2c0ab4a50f13e4 to your computer and use it in GitHub Desktop.
Incorporating compile time and runtime validation using refinement types in Scala
This file contains 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
import cats.data.ValidatedNec | |
import cats.implicits._ | |
import eu.timepit.refined._ | |
import eu.timepit.refined.api.Refined | |
import eu.timepit.refined.auto._ | |
import eu.timepit.refined.numeric._ | |
import eu.timepit.refined.collection._ | |
object person { | |
type ValidationResult[A] = ValidatedNec[String, A] | |
// compile time validation | |
type Age = Int Refined Positive | |
type Name = String Refined NonEmpty | |
// constructor that can be used for compile time type checks | |
case class Person private (name: Name, address: String, age: Age) | |
object Person { | |
// smart constructor for runtime validation | |
// that uses applicative style error accumulation | |
def person( | |
name: String, | |
address: String, | |
age: Int | |
): ValidationResult[Person] = { | |
(validateName(name), validateAge(age)).mapN { (n, a) => | |
Person(n, address, a) | |
} | |
} | |
def validateName(name: String): ValidationResult[Name] = | |
refineV[NonEmpty](name).fold(_.invalidNec, _.validNec) | |
def validateAge(age: Int): ValidationResult[Age] = | |
refineV[Positive](age).fold(_.invalidNec, _.validNec) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Gabriel's (@volpegabriel87) version: