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:
- Enhances the readability of the null value, expressing the wish that "I am hoping that there will be no result" ;
- 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