scala Option, None and Some

The appearance of option is to resolve the various ambiguities of null. The most common situation is to assume that we want to value a map, and we call the Map.get("key") method. In java, if the result is null, it may mean that the "key" exists, but the corresponding value is Empty, it may also mean that the "key" does not exist in the map. Therefore, there is an option class in scala to solve the problem of returning null. 
  In Java, null is a keyword, not an object, so calling any method on it is illegal. But this is a puzzling choice for language designers. Why return a keyword when the programmer expects to return an object? To be more consistent with the goal of everything being an object, and to follow functional programming conventions, Scala encourages you to use the Option type when variables and function return values ​​may not refer to any value. When there is no value, use None. If there is a value to refer to, use Some to contain the value. none and some are subclasses of option.

val temp = Map(
  "a" -> "A",
  "b" -> "B",
  "c"->"C",
  "d"->"D",
"e"->null
)
println( "a: " + temp.get("a").get )
println( "b: " + temp.get("b").get )
println( "e: " + temp.get("e").get)
//会报Exception in thread "main" java.util.NoSuchElementException: None.get错
//println( "f: " + temp.get("f").get)
println( "f: " + temp.get("f").getOrElse("F"))

The output is as follows:

a: A
b: B
e: null
f: F

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324959724&siteId=291194637