Option and Either Types in Scala

 Option and Either Types in Scala


Scala includes two types, Option and Either, which are often used in functional programming. Option represents a value that may or may not be present, while Either represents a value that can be one of two possible types. Here's an example of Option:

scss


val nameMap = Map("John" -> 30, "Jane" -> 25)

val johnAge = nameMap.get("John") // johnAge is now an Option[Int]


johnAge match {

  case Some(age) => println(s"John's age is $age.")

  case None => println("John's age is unknown.")

}

And here's an example of Either:


scss


def divide(x: Int, y: Int): Either[String, Int] = {

  if (y == 0) {

    Left("Cannot divide by zero!")

  } else {

    Right(x / y)

  }

}


val result1 = divide(10, 2) // result1 is now Right(5)

val result2 = divide(10, 0) // result2 is now Left("Cannot divide by zero!")

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...