Skip to content

Instantly share code, notes, and snippets.

@tototoshi
Created August 23, 2012 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tototoshi/3436143 to your computer and use it in GitHub Desktop.
Save tototoshi/3436143 to your computer and use it in GitHub Desktop.
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