使用scalaz的左,右,右的简单示例

时间:2017-04-07 20:07:50

标签: scala scalaz

如何使用scalaz实现这样的事情?取自here

的示例
object MyObject {

  def divideXByY(x: Int, y: Int): Either[String, Int] = {
    if (y == 0) Left("Cannot divide by 0")
    else Right(x / y)

  }

  def main(args: Array[String]) {

    println(divideXByY(12, 3))
    println(divideXByY(12, 0))

    divideXByY(12, 3) match {
      case Right(a) => println(s"We got: ${a}")
      case Left(b) => println(s"We got: ${b}")
    }
  }
}

1 个答案:

答案 0 :(得分:3)

import scalaz.{-\/, \/, \/-}

object MyObject {

  def divideXByY(x: Int, y: Int): Either[String, Int] = {
    if (y == 0) Left("Cannot divide by 0")
    else Right(x / y)

  }

  def divideXByYScalaz(x: Int, y: Int): \/[String, Int] = {
    if (y == 0) -\/("Cannot divide by 0")
    else \/-(x / y)
  }

  def main(args: Array[String]) {

    println(divideXByY(12, 3))
    println(divideXByY(12, 0))

    divideXByY(12, 3) match {
      case Right(a) => println(s"We got: ${a}")
      case Left(b) => println(s"We got: ${b}")
    }

    println("Working with scalaz")

    println(divideXByYScalaz(12, 3))
    println(divideXByYScalaz(12, 0))

    divideXByYScalaz(12, 3) match {
      case -\/(a) => println(s"We got: ${a}")
      case \/-(b) => println(s"We got: ${b}")
    }
  }
}