Question | Click to View Answer |
What does the following code return? new java.net.URL("this is invalid")
|
The |
What does the following code return? val u = new java.net.URL("https://mungingdata.com/")
println(u.getProtocol)
|
The input supplied to the constructor is valid, so a Java libraries are easily accessible in Scala code. |
What does the following code return? import scala.util.Try
Try(new java.net.URL("this is invalid"))
|
|
What does the following code return? import scala.util.Try
Try(new java.net.URL("https://www.mungingdata.com"))
|
|
What does the following code print? val url = Try(new java.net.URL("https://www.blah.com"))
val res = if (url.isSuccess) "we have a URL" else "where to go?"
println(res)
|
You can call There is also an |
What does the following code print? val url = Try(new java.net.URL("blah"))
println(url.getOrElse("I am broken"))
|
The This allows for Try values to be handled in a functional way. |
What does the following code print? val url = Try(new java.net.URL("blah"))
println(url.map(_.getProtocol))
|
The URL cannot be parsed and we're calling the If we weren't using Scala's functional error handling, this code would error out. Scala wraps the error in a return value, so the code does not blow up and the error value can be processed in a functional manner. |
What does the following code print? val url = Try(new java.net.URL("https://www.mungingdata.com"))
println(url.map(_.getProtocol))
|
The return type is The URL is successfully parsed in this example and we can grab the protocol in a functional manner. |
What does the following code print? def toInt(s: String): Try[Int] =
Try(Integer.parseInt(s.trim))
println(toInt("80"))
|
The |
What does the following code print? def toInt(s: String): Try[Int] =
Try(Integer.parseInt(s.trim))
println(toInt("hello"))
|
The string "hello" cannot be parsed into an integer. |
What does the following code print? def toInt(s: String): Option[Int] = {
try {
Some(Integer.parseInt(s.trim))
} catch {
case e: Exception => None
}
}
println(toInt("55"))
println(toInt("hello"))
|
We can deal with exceptions in a functional manner with Option / Some / None, but it's awkward. It's better to deal with exceptions in a functional manner using Try / Success / Failure. |