Good programmers large series of data samples based tutorial Scala _Option_ partial functions, in Scala Option type class used to represent the sample values may or may not exist (Option and subclasses has Some None). Some packaging a certain value, None indicates 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)
//更好的方式
val v1 = map.getOrElse("c", 0)
println(v1)
}
}
Partial function
is a packet does not match the set of case statements in braces is a partial function, which is an example PartialFunction [A, B] of, A representative of the parameter type, B for the return type, commonly used as an input pattern matching
object PartialFunctionDemo {
def f: PartialFunction[String, Int] = {
case "one" => 1
case "two" => 2
// case _ => -1
}
main DEF (args: Array [String]) {
// call f.apply ( "One")
println (f ( "One"))
println (f.isDefinedAt ( "Three"))
// throws MatchError
println (f ( "Three"))
}
} iNTERPOLATION string (string interpolation) (Optional)
use: string type processing:
s: string interpolation
f: interpolation and output format
raw: string outputted without any conversion
Scala 2.10.0 after introduction of the new mechanism to create a string, i.e. it allows the user to directly String Interpolation string. embedded references to variables.
val name="James"
println(s"Hello,$name") // Hello, James
Location string interpolation expression may be put, as follows:
println(s"1 + 1 = ${1 + 1}")// 1 + 1 = 2
F interpolation can be formatted string, 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
similar raw s, raw but without any contents of string conversion:
scala> s"a\nb"
res0: String =
a
b
scala> raw"a\nb"
res1: String = a\nb