Good programmer big data tutorials share the Option_ partial function of Scala series _ String
Good programmer big data tutorials share the Option_ partial function of Scala series _ String
Option Typ
In Scala, the Option type sample class is used to represent values that may or may not exist (subclasses of Option are Some and None). Some wraps a value, and None means no value.
Object OptionDemo {
Def main (args: Array [String]) {
Val map = Map ("a"-> 1, "b"-> 2)
Val v = map.get ("b") match {
Case Some (I) = > I
Case None = > 0
}
Println (v)
/ / A better way
Val v1 = map.getOrElse ("c", 0)
Println (v1)
}
}
Partial function
A set of case statements that are wrapped without match in curly braces is a partial function, which is an instance of PartialFunction [A, B], where A represents the parameter type and B represents the return type, often used as an input pattern match
Object PartialFunctionDemo {
Def f: PartialFunction [String, Int] = {
Case "one" = > 1
Case "two" = > 2
/ / case _ = >-1
}
Def main (args: Array [String]) {
/ / call f.apply ("one")
Println (f ("one"))
Println (f.isDefinedAt ("three"))
/ / throw MatchError
Println (f ("three"))
}
} String INTERPOLATION (string interpolation) (alternative)
Purpose: dealing with string types:
S: string interpolation
F: interpolate and format the output
Raw: output without any transformation on the string
After Scala 2. 10. 0, a new mechanism for creating strings, String Interpolation. 0, is introduced. It allows the user to embed a reference to a variable directly in a string.
Val name= "James"
Println (s "Hello,$name") / / Hello, James
The position of string interpolation can also be expressed as follows:
Println (s "1 + 1 = ${1 + 1}") / / 1 + 1 = 2
Interpolation f can format strings, similar to printf:
Val height = 1.9d
Val name = "James"
Println (f "$name%s is $height%2.2f meters tall") / / James is 1.90 meters tall
Raw is similar to s, but raw does not convert the contents of the string:
Scala > s "a\ nb"
Res0: String =
A
B
Scala > raw "a\ nb"
Res1: String = a\ nb