Good programmer big data tutorial sample class of Scala series _ Option_ partial function
A good programmer big data tutorial Scala series sample class_Option_partial function, in Scala Option type sample class is used to represent values that may or may not exist (Option subclasses are Some and None). Some wraps a value, 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 enclosed in braces without a match 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 input pattern matching.
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"))
//MatchError thrown
println(f("three"))
}
}String INTERPOLATION(optional)
Purpose: Processing String Type:
s: string interpolation
f: Interpolate and format output
raw: output without any transformation of the string
After Scala 2.10.0, a new mechanism for creating strings was introduced, namely String Interpolation. It allows users to embed references to variables directly in strings.
val name="James"
println(s"Hello,$name") // Hello, James
A string interpolation can also be placed in an expression, 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 string contents:
scala> s"a\nb"
res0: String =
a
b
scala> raw"a\nb"
res1: String = a\nb