Scala : Either, Left, Right Example
// Either... Left.. Right
scala> def menu(day:String): Either[Int,String] = {
| if (day == "Sunday") Right("Fish Curry")
| else if (day == "Monday") Right("Veg Fry")
| else Left(0)
menu: (day: String)Either[Int,String]
Right(Fish Curry)
Right(Veg Fry)
Left(0)
menu(input) match {
case Left(a) => println("Left Answer is : " + a)
case Right(b) => println("Right Answer is : " + b)
Right Answer is : Fish Curry
c: Either[Int,String] = Right(Veg Fry)
res3: Boolean = true
res4: Boolean = false
c: Either[Int,String] = Right(Veg Fry)
scala>
res6: Boolean = true
input: String = Sunday
res7: Any = ()
res1: Any = Right(())
c: Either[Int,String] = Right(Veg Fry)
res3: Either[Int,String] = Right(Veg Fry)
res8: Option[Int] = None
res9: Option[String] = Some(Veg Fry)
def divideXByY(x: Int, y: Int): Either[String, Int] = {
if (y == 0) Left("Dude, can't divide by 0")
else Right(x / y)
}
println(divideXByY(1, 0))
divideXByY(1, 0) match {
case Left(s) => println("Answer: " + s)
case Right(i) => println("Answer: " + i)
}
}
scala> def menu(day:String): Either[Int,String] = {
| if (day == "Sunday") Right("Fish Curry")
| else if (day == "Monday") Right("Veg Fry")
| else Left(0)
| }
scala> println(menu("Sunday"))
scala> println(menu("Monday"))
scala> println(menu("Tuesday"))
menu(input) match {
case Left(a) => println("Left Answer is : " + a)
case Right(b) => println("Right Answer is : " + b)
}
scala> val c = menu("Monday")
scala> c.isRight
scala> c.isLeft
scala> val c = menu("Monday")
scala> c.isLeft
res5: Boolean = false
scala> c.isRight
scala> val input = "Sunday"
scala> if (menu(input).isLeft) menu(input).left.map( a => println("Answer is : " + a))
scala> if (menu(input).isRight) menu(input).right.map( b => println("Answer is : " + b))
Answer is : Fish Curry
scala> val c = menu("Monday")
scala> c
scala> c.left.toOption
scala> c.right.toOption
def divideXByY(x: Int, y: Int): Either[String, Int] = {
if (y == 0) Left("Dude, can't divide by 0")
else Right(x / y)
}
// a few different ways to use Either, Left, and Right
println(divideXByY(1, 1))
case Left(s) => println("Answer: " + s)
case Right(i) => println("Answer: " + i)
}
}
No comments:
Post a Comment