What is Option[T]?
Official definition:
It represent optional values. Instances of option are either an instance of Some or the object None.
Simple definition:
It's a container.
Java approach
Scala approach
val person:Person = getPersonById(id)
if (person != null) {
getEmail(person);
}val maybePerson: Option[Person] = getPersonById(id)
maybePerson match {
case Some(person) => getEmail(person)
case None => // do nothing or something else}
Dishonest:
Honest:
def getPersonById(id: Int):Person def getPersonById(id: Int):Option[Person]Imagine Option as a collection of 1 or o elements.
Chaining multiple function calls:
val x: Option[Int] = getPerson()
x.foreach(person =>getEmail(person))getPerson().map(getEmail(_))
.map(getHost(_))
.map(writeToDb(_))
What is Try[T]?
Official definition:
The Try type represents a computation that may either result in an exception, or return a successfully computed value.
Simple definition:
It's a container.
Java approach
Scala approach
URL parseURL(String url) throws MalformedURLException {
try { new URL(url); }
catch(MalformedURLException e){
throw e;
}
}
def parseURL(url: String): Try[URL] = Try(new URL(url))
Or
parseURL(url) match {
case Success(url) => url
case Failure(ex) => Log.error(ex)
} parseURL(url) .map(url => openConnection(url)) for {
url <- parseURL(url)
connection <- Try(url.openConnection())
stream <- Try(connection.getInputStream)}
yield stream