wix-incubator / accord

Accord: A sane validation library for Scala
http://wix.github.io/accord/
Other
529 stars 55 forks source link

call validation function based on class of object as explained #161

Closed sudhirkumar1980 closed 3 years ago

sudhirkumar1980 commented 3 years ago

Following Person and Adult class has Implicit Validator functions. Adult class extends the Person class trait Person { def name: String def surname: String def age: Int }

object Person { implicit val taskValidator: Validator[ Person ] = validator[ Person ] { person => println("personValidator") person.name is notEmpty person.surname is notEmpty person.age is between( 0, 120 ) } }

case class Adult( name: String, surname: String, age: Int, contactInfo: String ) extends Person

case object Adult { implicit val taskValidator: Validator[ Adult ] = validator[ Adult ] { adult => println("adultValidator") adult is valid( Person.taskValidator ) adult.age should be >= 18 adult.contactInfo is notEmpty }

}

validAdult variable is of Person class is assigned to Adult class object. When calling validate on validAdult, it calls Validator function from Person class object instead of Adult. how can we make it to call Validator function from Adult? We dont want to change variable type to Adult. val validAdult:Person = Adult( name = "Grace", surname = "Hopper", age = 85, contactInfo = "Arlington National Cemetery" ) val result=validate( validAdult) println(result)

noam-almog commented 3 years ago

this is an implicit question and not an accord question : )

inheritance is an issue, when trying to evaluate the validate scala needs to have a concrete class or just know what the type is. when you are working in an interface you can either tell accord which validator to use explicitly or do the resolving yourself, pattern match according to class type and validate when type is known.

sudhirkumar1980 commented 3 years ago

Thank you. I will close it.