Created
August 23, 2012 12:16
-
-
Save tototoshi/3436143 to your computer and use it in GitHub Desktop.
Trying scala.util.Try
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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