"Scala" uses option, Some, None, to avoid using null

Source: Internet
Author: User

Avoid null use

Most languages have a special keyword or object that represents an object that refers to a "none", in Java, which is null. In Java, null is a keyword, not an object, so it is illegal to call any method on it. But this is a confusing choice for language designers. Why do you want to return a keyword when the programmer wants to return an object?

The option type of Scala

In order for everything to be more consistent with the object's goal, and to follow the habit of functional programming, Scala encourages you to use the option type when variables and function return values may not reference any value. In the absence of a value, use None, which is a subclass of option. If a value can be referenced, use some to include the value. Some is also the subclass of option.
None is declared as an object, not a class, because we only need one instance of it. This way, it's somewhat like a null keyword, but it's a real, method-aware object.

Application examples

The value of the option type is typically the return type of the Scala collection type (LIST,MAP, etc.) operation. For example, the Get method of map:

scala> val  Capitals = Map ( "France" -> "Paris" ,  "Japan" -> "Tokyo" ,  "China" -> "Beijing" ) capitals:scala.collection.immutable.map[string,string] = Map (France-Paris, Japan, Tokyo, China--Beijing) scala> Capitals get  "France" /span>res0:option[string] = Some (Paris) scala> capitals get  "North Pole"  res1: Option[string] = None  

Option has two subcategories, some and none. When the program returns to the some, this function successfully gives you a string, and you can get the string through the Get () function, if the program returned none, then there is no string to give you.
When you return none, that is, there is no string for you, if you are hard to call get () to get a string, Scala will throw a nosuchelementexception exception Here you are.
We can also choose another method, Getorelse. This method returns the corresponding value when the option is an instance of some, and returns the passed-in argument when the instance is none. In other words, the parameter passed in Getorelse is actually the default return value.

scala> capitals get  "North Pole"  getwarning: There was one feature warning; Re-run with -feature for  Detailsjava.util.NoSuchElementException:None.get at Scala. None$.get (Option.scala:347 ) at Scala. None$.get (Option.scala:345 ) ... 33  elidedscala> Capitals get  "France"  Getwarning:there was one feature warning; Re-run with -feature for  detailsres3:string = Parisscala> (Capitals get  "North Pole" ) getorelse  " Oops " res7:string = oopsscala> capitals get " France " getorelse " Oops " res8:string = Paris 

The optional values are separated by pattern matching, and if the matching values are some, the values in the some are extracted to the X variables:

defmatch {    case Some(s) => s    case"?"}
Tips

The Scala program uses option very frequently, using NULL in Java to represent null values, and many places in the code to add the NULL keyword detection, otherwise it is easy to appear nullpointexception. So Java programs need to be concerned about those variables that might be null, and the likelihood of these variables appearing null is very low, but it is difficult to find out why nullpointerexception occurs.
Scala's option type avoids this, so the Scala app recommends using the option type to represent some of the optional values. With the option type, the reader can see at a glance that the value of this type may be none.

In fact, thanks to Scala's static type, you can't mistakenly try to invoke a method on a potentially null value. Although this is a very easy mistake in Java, it does not compile in Scala because there is no programming in Java to check if a variable is null as a type error in Scala (you cannot use option[string] as a String). Therefore, the use of option strongly encourages more flexible programming practices.

Detailed Option[t]

In Scala, Option[t] is actually a container, just like an array or list, and you can think of it as a list that might have 0 to one element.
When there is something in your option, the list length is 1 (that is, Some), and when there is nothing in your option, its length is 0 (that is, none).

For loop

If we use option as a generic list and use a For loop to visit this option, if option is None, then the program code in this for loop will not be executed, so we have reached the " Don't check if option is none.

val map1 = Map("key1""value1"val value1 = map1.get("key1"val value2 = map1.get("key2"def printContentLength(x: Option[String]) {     |   for (c <- x){     |     println(c.length)     |   }     | }printContentLength: (x: Option[String])Unitscala> printContentLength(value1)6scala> printContentLength(value2)
Map operations

One of the core concepts in functional programming is the conversion, so most of the supported functional programming languages support an action called map (), which can help you to turn the contents of a container into another new container after some action.
Now let's consider how to use the option Map method to implement length: xxx the output form:

The length of the string within the Option container is calculated first
Then add the words "Length:" In front of the length.
Finally, the container was visited once, and the contents of the container were printed out

scala> value1.map(_.length).map("length: "6scala> value1.map("length: "6

Through this "transformation" method, we can achieve the desired effect, but also do not have to do "is none" judgment. "

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, Some, None, to avoid using null

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.