The Scala option type is used to indicate that a value is optional (either a value or no value).
OPTION[T] is a container of an optional value of type T: If the value exists, Option[t] is a some[t], if not, Option[t is the object None.
Next, let's take a look at the code:
Although Scala can not define the type of the variable, in order to be clear, I still
//Put the definition of his display on
Val mymap:map[string, String] = Map ("Key1"-> "value")
VA L value1:option[string] = Mymap.get ("Key1")
val value2:option[string] = mymap.get ("Key2")
println (value1)// Some ("value1")
println (value2)//None
In the above code, mymap a type of a Key is the type of string,value is a hash map of String, but the difference is that his get () returns a category called Option[string].
Scala uses option[string to tell you: "I'll find a way to return a string, but there may not be a string for you."
There is no key2 this data in the Mymap, and the Get () method returns none.
Option has two subcategories, one is Some, one is None, and when he returns Some, the function succeeds in giving you a string, and you can get that string through the function, and if he is returning none, It means no strings can be given to you.
Another instance:
Object Test {
def main (args:array[string]) {
Val sites = Map ("Runoob"-> "www.runoob.com", "Google"-> "www . Google.com ")
println (" Sites.get (\ runoob\ "):" + sites.get ("Runoob"))//Some (www.runoob.com)
println ("Sites.get (\ baidu\"): "+ Sites.get (" Baidu ")) // None
}
}
Execute the above code and the output is:
$ Scalac Test.scala
$ scala Test
sites.get ("Runoob"): Some (www.runoob.com)
sites.get ("Baidu"): None
You can also output matching values through pattern matching. Examples are as follows:
Object Test {
def main (args:array[string]) {
Val sites = Map ("Runoob"-> "www.runoob.com", "Google"-> "www . Google.com ")
println (" Show "(Sites.get (\ runoob\)):" + Show
(Sites.get ("Runoob"))
println ("Show" ( Sites.get (\ "Baidu\")): "+ Show
(Sites.get (" Baidu))
} def show
(x:option[string]) = x Match {
case so Me (s) => s case
None => "?"
}
Execute the above code and the output is:
$ Scalac Test.scala
$ scala Test show
(Sites.get ("Runoob")): Www.runoob.com Show
(Sites.get ("Baidu"))