Search code examples
scalascala-cats

How to return Left item from Validated?


I have a method that returns the following:

def myMethod(): Validated[List[MyError], MyClass] {
 ...
}

I have another method that expects List[MyError]

def otherMethod(errors: List[MyError]) { 
  ...
}

How can I call otherMethod with List[MyError] being returned from myMethod. Like below:

otherMethod(myMethod())

The above doesn't work and gives compilation error:

expected: List[MyError], actual: Validated[List[MyError], MyClass]

Solution

  • There are two possible outcomes of myMethod execution: it either . returns a list of errors or (presumably) a result of type MyClass. You are only talking about handling one of these outcomes. That is wrong. You should always keep both in mind, and handle them together. For example:

       myMethod() match {
         case Left(errors) => otherMethod(errors)
         case Right(result) => yetAnotherMethod(result)
       }