Try type in Scala

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


scss


import scala.util.{Try, Success, Failure}


def divide(a: Int, b: Int): Try[Double] = Try(a.toDouble / b.toDouble)


val result1 = divide(10, 5)

val result2 = divide(10, 0)


result1 match {

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

  case Failure(error) => println(s"An error occurred: ${error.getMessage}")

}


result2 match {

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

  case Failure(error) => println(s"An error occurred: ${error.getMessage}")

}

In this example, the divide function takes two integers and returns a Try[Double] representing the result of dividing the first number by the second. If an exception is thrown during the division operation (e.g. if the second number is zero), the Try value will be a Failure containing the exception. Otherwise, it will be a Success containing 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 Try value and print the appropriate output. If the value is a Success, the underlying value is printed to the console. If the value is a Failure, a message indicating that an error occurred is printed along with the exception message.


This example demonstrates how the Try type can be used to represent the result of an operation that may throw an exception, and how pattern matching can be used to handle the success or failure of the operation in a concise and readable way.

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