1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2016-11-25

モチベーション

任意の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))
1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?