Pacific-Design.com

    
Home Index

1. Scala

2. 6 Option

Scala / 6 Option /

Scala Option

/*1. fold */
nextOption.fold(-1)(x => x)

/* 2. getOrElse  */
nextOption getOrElse 5 or nextOption getOrElse { println("error!"); -1 }

/* orElse */
nextOption orElse nextOption

/* Match expressions */
nextOption match { 
    case Some(x) => x
    case None => -1 
}

Avoid Option.get() -> Option.getOrElse

Option.get() is unsafe and should be avoided, because it disrupts the entire goal of type-safe operations and can lead to runtime errors. If possible, use an operation like fold or getOrElse that allows you to define a safe default value.

scala> def nextOption = if (util.Random.nextInt > 0) Some(1) else None
nextOption: Option[Int]

scala> val a = nextOption
a: Option[Int] = Some(1)

scala> val b = nextOption
b: Option[Int] = None

Try Catch

scala> val input = " 123 "
input: String = " 123 "

scala> val result = util.Try(input.toInt) orElse util.Try(input.trim.toInt)
result: scala.util.Try[Int] = Success(123)

scala> result foreach { r => println(s"Parsed '$input' to $r!") }
Parsed ' 123 ' to 123!

scala> val x = result match {
     |   case util.Success(x) => Some(x)
     |   case util.Failure(ex) => {
     |     println(s"Couldn't parse input '$input'")
     |     None
     |   }
     | }
x: Option[Int] = Some(123)