Scala Data interaction
Scala uses a functional way to manipulate data interactions, including the entry and return values.
- Option: Resolve null (NULL pointer) issues
- Either: Resolve return value indeterminate (one of two values returned) issue
- Try: Resolving a function may throw an exception problem
Use of Option/some/none
Option actually has 3 types: option, some and none,some, and none are the subtypes of option, some and none. option represents an optional value, and its return type is scala.Some
or scala.None
. Some represents the return of valid data, none represents a null value.
function that returns the option object
The function takes a string object as input, if the string object is correctly converted to an Int object, returns Sone[int]; otherwise none is returned:
def toInt(s: String): Option[Int] = { try { Some(Integer.parseInt(s.trim)) catch { case e : Exception => None }}
Use option in a Scala collection class
Suppose you have a list of strings, and we want to get all the integers in the list, by passing the ToInt method into the map method of the list object, converting the listing element to the some or none value:
Scala>ValBag = List ("1","2","foo","4","Bar") bag:list[string] = List (1,2Foo4, bar)//Convert the original Option object list to an integer list by flatten//Because option is a collection that contains one element or 0 elements (None), the conversion can be madeScala> Bag.map (ToInt). Flattenres1:list[int] = List (1,2,4)//Achieve the same conversion through FlatmapScala> Bag.flatmap (toint) Res2:list[int] = List (1,2,4)//using the Collect method to achieve the same functionScala> Bag.map (toint). collect{ CaseSome (i) = i}res12:list[int] = List (1,2,4)
The higher order function of option
The following function prints the length of a string in a Option[string] object, which uses the option's Map method and the Foreach method:
def printContentLength(x: Option[String]): Unit = { x.map("length: " + _.length).foreach(println)}val value1 = Some("value1")val//length: 6//无打印
Here is the string from the option[string] object trimmed and converted to uppercase:
def trimUpper(x: Option[String]): Option[String] = { x map (_.trim) filter (!_.isEmpty) map (_.toUpperCase)}val name1 = Some(" name ")val//Some(NAME)//None
Use of Try/success/failue
In a similar approach to ReadFile, we will use the try catch syntax. SCALA2.10 provides a try to more gracefully implement this function. For operations that are likely to throw an exception. We can wrap it with a try, get the subclass of the try success or failure, if the calculation succeeds, return an instance of success, and if an exception is thrown, return failure and carry the relevant information.
ImportScala.util. {Try, Success, Failure}defDivideby (X:int, Y:int): try[int] = {Try (x/y)}println (Divideby (1,1). Getorelse (0))//1println (Divideby (1,0). Getorelse (0))//0Divideby (1,1). foreach (println)//1Divideby (1,0). foreach (println)//No printDivideby (1,0)Match{ CaseSuccess (i) = println (s"Success, value is: $i") CaseFailure (s) = println (s"Failed, message is: $s")}//failed, message is:java.lang.ArithmeticException:/by Zero
ReadTextFile Example
If the method returns successfully, the contents of the file will be printed, and /etc/passwd
if an exception occurs, the error message will be printed.java.io.FileNotFoundException: Foo.bar (No such file or directory)
def readTextFile(filename: String): Try[List[String]] = { Try(Source.fromFile(filename).getLines.toList)}val"/etc/passwd"match { case Success(lines) => lines.foreach(println) case Failure(f) => println(f) }}
Other than that
- Try has a similar set of operations filter, FLATMAP, flatten, foreach, map
- Get, Getorelse, OrElse method
- Tooption can be converted to option
- Recover,recoverwith,transform allows you to gracefully handle the results of success and failure.
Use of Either/left/right
This is often required in programming, where a function (or method) returns different values when passing in different parameters. The return value is two unrelated types: left and right. We generally believe that left contains errors or invalid values, and right contains correct or valid values.
Before Scala 2.10, the Either/right/left class and the Try/success/failure class were similar effects.
def divideBy2(x: Int, y: Int): Either[String, Int] = { if0) Left("Dude, can‘t divide by 0") else Right(x / y)}divideBy2(10match { case Left(s) => println("Answer: " + s) case Right(i) => println("Answer: " + i)}//print "Answer: Dude, can‘t divide by 0"
In addition to using the Match case method to get the data, we can also use the. Right.get and. Left.get methods separately, and of course you need to use. isright or. Isleft to judge first. The left or right types also have filter, FlatMap, foreach, GET, Getorelse, map methods, and they also have tooption, TOSEQ methods, which return an option or SEQ, respectively.
reprint Please indicate the author Jason Ding and its provenance
Gitcafe Blog Home page (http://jasonding1354.gitcafe.io/)
GitHub Blog Home page (http://jasonding1354.github.io/)
CSDN Blog (http://blog.csdn.net/jasonding1354)
Jane Book homepage (http://www.jianshu.com/users/2bd9b48f6ea8/latest_articles)
Google search jasonding1354 go to my blog homepage
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Scala" uses option, either, and try to manipulate data interactions