Scala

Scalaz.ValidationでOption型の中身を検証する方法

More than 1 year has passed since last update.


モチベーション

任意のA型を検証するバリデーションをOption[A]型の検証にも使いたい。Noneのときはバリデーションを実行したくない。


実装

import scalaz._

import Scalaz._

object PresenceValidator {
def apply(value: String): ValidationNel[String, String] =
if (value.trim.isEmpty) "Can't be blank".failureNel
else value.successNel
}

object OptionalValidator {
def apply[A](value: Option[A])(f: A => ValidationNel[String, A]): ValidationNel[String, Option[A]] =
value match {
case Some(v) => f(v).map(_.some)
case None => value.successNel
}
}


使い方

case class User(screenName: String, nickname: Option[String])

object Main extends App {
val user1 = User("tarou", Some("Tarou Yamada"))
val user2 = User("tarou", Some(""))
val user3 = User("tarou", None)

val res1 = (PresenceValidator(user1.screenName) |@| OptionalValidator(user1.nickname)(PresenceValidator.apply))(User)
val res2 = (PresenceValidator(user2.screenName) |@| OptionalValidator(user2.nickname)(PresenceValidator.apply))(User)
val res3 = (PresenceValidator(user3.screenName) |@| OptionalValidator(user3.nickname)(PresenceValidator.apply))(User)

println(res1)
println(res2)
println(res3)
}


実行結果

Success(User(tarou,Some(Tarou Yamada)))

Failure(NonEmpty[Can't be blank])
Success(User(tarou,None))