19-option types of Scala learning notebooks

Source: Internet
Author: User

When you see the option type, you know that the textbook should say that.

Once you have used guava, you should know what the optional class in guava is for. Well, look for the original document:

Optional<t> is a-replacing a nullable T reference with a non-null value. An Optional could either contain a non-null T reference (in which case we say the reference are "present"), or it may contain Nothing (in which case we say the reference is "absent"). It is never said to "contain null."

In a word, the role of optional in guava is to avoid using null directly.

The role of the option class in Scala is consistent with the optional meaning of guava. Their significance lies in two points:

    1. Enhances the readability of the null value, expressing the wish that "I am hoping that there will be no result" ;
    2. For code usability reasons, the developer is forced to proactively check that the value of the object is null.

Look at an example:

def commentonpractice (input:string) = {  //rather than returning null  if ( Input = = "Test") Some ("good")  else    None}for (input <-Set ("Test", " Hack ")) {  = commentonpractice (input)  println (" input "+ input +" comment "+ comment.get OrElse ("Found No Comments"))}

The Commentonpractice () in the code may return a string, and perhaps nothing will return. In this method, the some[t] and none instances were used to deal with the two possible scenarios. Some[t] and none are option[t] subclasses. Let's take a look at the results:

Explicitly declaring a type as Option[string],scala forces us to check that the instance does not exist. As a result, nullpointerexception is less likely to be thrown because null references are not checked. Call the Getorelse () method that returns OPTION[T] to proactively respond to a situation where the result does not exist (None).

That's it.

########

19-option types of Scala learning notebooks

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.