如何使用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}")
}
}
}
答案 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}")
}
}
}