Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Trying scala.util.Try
import scala.util.{ Try, Success }
import scala.util.control.Exception._
object Main extends App {
val result = for {
i <- Try("abc".toInt) recover {
case e: NumberFormatException => 1
}
j <- Try("2".toInt)
} yield {
i + j
}
assert(result == Success(3))
}
import scala.util.{ Try, Success }
import scala.util.control.Exception._
object Main extends App {
def asInt(s: String): Try[Int] = {
Try(s.toInt).transform({
i => Try(i)
}, {
e => Try(0)
})
}
assert(asInt("abc") == Success(0))
assert(asInt("1") == Success(1))
}
import scala.util.{ Try, Success }
object Main extends App {
val result = for {
x <- List("a", "1", "2", "3", "b", "c")
i <- Try(x.toInt).recover { case e: NumberFormatException => 0 }.toOption
} yield {
i
}
println(result)
}
import scala.util.{ Try, Success }
object Main extends App {
val result = for {
x <- List("a", "1", "2", "3", "b", "c")
i <- Try(x.toInt).recover { case e: NumberFormatException => 0 }.toOption
if i > 0
} yield {
i
}
assert(result == List(1, 2, 3))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment