10

I've been looking but I can't find an implicit converter. Obviously it would be trivial to write one but I'm wondering if I've missed one in the scalaz library somehow!

Noel Kennedy
  • 12,128
  • 3
  • 40
  • 57

2 Answers2

12

Scalaz has a implicit conversion of Option to OptionW, which declares the toFailure and toSuccess methods.

Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
0

Basically you have methods that transform "Some" into the "happy path" (in case of Validation -> Success, in case of Disjunction \/-) and then you need to define an error description for the None.

I use this when I receive an Optional parameter and I want to raise an error if is not provided.

Example:

scala> import scalaz.Scalaz._
import scalaz.Scalaz._

scala> import scalaz._
import scalaz._

scala> Some("clientId123").toSuccessNel("Client id is mandatory")
res0: scalaz.ValidationNel[String,String] = Success(clientId123)

scala> None.toSuccessNel("Client id is mandatory")
res1: scalaz.ValidationNel[String,Nothing] = Failure(NonEmpty[Client id is mandatory]) 

If you accumulate the errors using applicatives you can give a comprehensive error message to the final user, something like:

Client id is mandatory, country is mandatory, etc
Carlos Verdes
  • 3,037
  • 22
  • 20