scala 構文4

パターンマッチ

case class Point(x: Int, y: Int)

object MyApp {

  def main(args: Array[String]): Unit = {

   var points = List(
    Point(5, 3),
    Point(0, 0),
    Point(3, 4)
   )
   points.foreach(_ match{
    case Point(0, 0) => println("original")
    case Point(5, _) => println("right edge")
    case Point(x, y) => println(s"$x:$y")
   })

  }

}

option型のエラー処理

object MyApp {

  def main(args: Array[String]): Unit = {
  val scores = Map("yoshimoto" -> 55, "kimoto" -> 65)
  scores.get("tanaka") match {
   case Some(v) => println(v)
   case None => println("key not found")
  }
  }

}

Eitherによるエラー処理

object MyApp {

 // Error Either - right, left

  def div(a: Int, b: Int): Either[String, Int] = {
  if (b == 0) Left("Zero div error!")
  else Right(a / b)
  }
  def main(args: Array[String]): Unit = {

   div(10, 2) match {
   case Right(n) => println(n)
   case Left(s) => println(s)
   }

  }

}