Creating an Either

Either[X, Y] is an instance that contains either an instance of X or an instance of Y but not both. We call these subtypes left and right of Either. Creating an Either is trivial. But it's very powerful sometimes to use it in your program:

package com.chapter3.ScalaFP
import java.net.URL
import scala.io.Source
object Either {
def getData(dataURL: URL): Either[String, Source] =
if (dataURL.getHost.contains("xxx"))
Left("Requested URL is blocked or prohibited!")
else
Right(Source.fromURL(dataURL))
def main(args: Array[String]) {
val either1 = getData(new URL("http://www.xxx.com"))
println(either1)
val either2 = getData(new URL("http://www.google.com"))
println(either2)
}
}

Now, if we pass any arbitrary URL that doesn't contain xxx then we will get a Scala.io.Source wrapped in a Right subtype. If the URL contains xxx, then we will get a String wrapped in a Left subtype. To make the preceding statement clearer, let's see the output of the preceding code segment:

Left(Requested URL is blocked or prohibited!) Right(non-empty iterator)

Next, we will explore another interesting feature of Scala called Future that is used to execute tasks in a non-blocking way. This is also a better way to handle the results when they finish.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.114.52