LoginSignup
12

More than 5 years have passed since last update.

ScalaのOption型とEither型を使う

Last updated at Posted at 2015-04-15

Option型とEither型について

両方とも例外が発生しうる状況において使える型になります。Option型は例外の有無(SomeかNone)をEither型は例外の有無に加え詳細(RightかLeft)を伝えることがそれぞれ可能です。Either型では正しいという意味のrightとRightをかけてRightに正しい方向に進んだ時の処理を書くみたいです。

入力された文字列にスペースが含まれていないか確かめる。

OptionEither.scala
object OptionEither {
  def main(args: Array[String]): Unit = {
    println("Please enter word.")
    val word = scala.io.StdIn.readLine
    validateByOption(word)
    validateByEither(word)
  }
  def validateByOption(word: String): Option[String] = {
    word.contains(' ') match {
      case true => None
      case false => Some(word)
    }
  }
  def validateByEither(word: String): Either[String, String] = {
    word.contains(' ') match {
      case true => Left("Error The Word Contains Space")
      case false => Right(word)
    }
  }
}

追記

コメント欄にてSomeは成功した場合の意味合いがあるとご指摘いただきましたので編集させていただきました、ありがとうございます。

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
12