Black monkey house: Scala option type

Scala provides a wrapper for a single target value, indicating the presence of a value may not exist for that possibility.
It has only two valid subclass object, is a s Some, represents a value, the other one is None, expressed as empty, by using Option, avoiding the use of null, empty string, etc. to a value representing the absence of practice. Avoid null pointer exception

scala> val map = Map("Alice" -> 20, "Bob" -> 30)
scala> println(map.get("Alice"))
some(20)
scala> println(map.get("Jone"))
None
scala> println(map.apply("Alice"))
20
scala> println(map ("Alice"))
20
scala> println(map("Jone"))
Exception in thread "main" java.util.NoSuchElementException: key not found: Nick1

Screaming Tip: Use the get method to get the value, not recommended apply the method to get the value, use the apply method to obtain, if not key, an exception will be reported by the example above it is to elicit option this concept, because just started learning scala this language, we have a lot of concepts, are not very clear, there is no time to come into contact with, so we just started to learn the language of the scala, the first thing we need to do, is to lead to many concepts, but will not be in-depth to explain, when behind in-depth to explain, for example, talked about the collection, we will again put option to pick out, here it, I just need to get to know the value of time, using the get method would be better

Reproduced in: https: //www.jianshu.com/p/1e7297466196

Guess you like

Origin blog.csdn.net/weixin_34279579/article/details/91182419