1
votes

I do validation of a form. Imagine we want to validate some subset of the Cat case class fields:

case class Cat(name: String, age: Int, weight: Double)

def validateCatName(name: String): ValidationResult[String]
def validateCatAge(age: Int): ValidationResult[Int]

def validateCatForm(cat: Cat): ValidationResult[Cat] = {
    (validateCatName(cat.name),
    validateCatAge(cat.age)
    ).mapN((_, _) => cat)
  }

I can not get idea of mapN((r1, ..., rN) => Result(r1, ..., rN)). For example in my case I have to do mapN((validatedName, validatedAge) => Cat(validatedName, validatedAge, cat.weight). Actually I want to ignore the validated results and escape some over re-mapping with the dumb params. Something like this:

def validateCatForm(cat: Cat): ValidationResult[Cat] = {
        (validateCatName(cat.name),
        validateCatAge(cat.age)
        ).ifValid(cat)
      }

Is it possible?

1
what did you finally go for ? - sashas

1 Answers

3
votes

You can ignore the arguments and return the cat directly:

def validateCatForm(cat: Cat): ValidationResult[Cat] = {
  (
    validateCatName(cat.name),
    validateCatAge(cat.age)
  ).mapN{ (_, _) => cat }
}

However, recall that it is usually the job of the constructor to ensure that every constructed Cat is actually valid. The validateCatForm should rather be accepting name and age directly, then you could write:

def validateCatForm(name: String, age: Int): ValidationResult[Cat] = {
  (
    validateCatName(name),
    validateCatAge(age)
  ).mapN{ new Cat(_, _) }
}

In this way, you would not force the users of your API to create any invalid Cats just in order to pass them to a form validation method.