Option type in Scala

 Here's an example of how to use the Option type in Scala:


scss


def divide(a: Int, b: Int): Option[Double] = {

  if (b == 0) None

  else Some(a.toDouble / b.toDouble)

}


val result1 = divide(10, 5)

val result2 = divide(10, 0)


result1 match {

  case Some(value) => println(s"The result is $value")

  case None => println("The operation is undefined")

}


result2 match {

  case Some(value) => println(s"The result is $value")

  case None => println("The operation is undefined")

}

In this example, the divide function takes two integers and returns an Option[Double] representing the result of dividing the first number by the second. If the second number is zero, the function returns None to indicate that the operation is undefined. Otherwise, it returns Some(result) where result is the division result.


Two examples are shown of using the divide function with different input parameters. The match keyword is used to pattern match on the resulting Option value and print the appropriate output. If the value is Some, it is printed to the console. If the value is None, a message indicating that the operation is undefined is printed.


This example demonstrates how the Option type can be used to represent values that may or may not exist in a safe and concise way, and how pattern matching can be used to extract the underlying value when it is present.

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...