Saturday 7 May 2022

Scala Function - Cond

 Cond function with Either type accepts an anonymous function which returns a boolean. If the anonymous function returns true then cond returns Right else Left.

Cond with PartialFunction accepts the value and passes it to partialFunction which returns a boolean. If a partial function returns true then cond returns true else false.

CondOpt works similar to Cond except it return None for false.

object MyBlog {
  def main(args: Array[String]): Unit = {
    condExample()
  }


  def condExample(): Unit = {
    val isAbove18 = (input: Int) => input > 18
    val res: Either[String, String] = Either.cond(isAbove18(20), "True", "False")
    println(s"Cond with Either: ${res}") // Right(True)

    val canDivide: PartialFunction[Int, Boolean] = {
      case input: Int if(input != 0 )  => true
    }

    val res2: Boolean = PartialFunction.cond(0)(canDivide)
    println(s"Partial Function with Cond: ${res2}")

    val res3: Option[Boolean] = PartialFunction.condOpt(0)(canDivide)
    println(s"Partial Function with condOpt: ${res3}") //None

    val res4 =  canDivide(0)
    println(s"${res4}") // MatchError: 0 (of class java.lang.Integer)

  }











No comments:

Post a Comment