Tutorial by Examples

Try

Using Try with map, getOrElse and flatMap: import scala.util.Try val i = Try("123".toInt) // Success(123) i.map(_ + 1).getOrElse(321) // 124 val j = Try("abc".toInt) // Failure(java.lang.NumberFormatException) j.map(_ + 1).getOrElse(321) // 321 Try("123...
Different data types for error/success def getPersonFromWebService(url: String): Either[String, Person] = { val response = webServiceClient.get(url) response.webService.status match { case 200 => { val person = parsePerson(response) if(!isVali...
The use of null values is strongly discouraged, unless interacting with legacy Java code that expects null. Instead, Option should be used when the result of a function might either be something (Some) or nothing (None). A try-catch block is more appropriate for error-handling, but if the function ...
When an exception is thrown from within a Future, you can (should) use recover to handle it. For instance, def runFuture: Future = Future { throw new FairlyStupidException } val itWillBeAwesome: Future = runFuture ...will throw an Exception from within the Future. But seeing as we can predic...
In addition to functional constructs such as Try, Option and Either for error handling, Scala also supports a syntax similar to Java's, using a try-catch clause (with a potential finally block as well). The catch clause is a pattern match: try { // ... might throw exception } catch { case i...
To convert exceptions into Either or Option types, you can use methods that provided in scala.util.control.Exception import scala.util.control.Exception._ val plain = "71a" val optionInt: Option[Int] = catching(classOf[java.lang.NumberFormatException]) opt { plain.toInt } val eitherI...

Page 1 of 1