Scala模式匹配Scala类型系统Spark源码阅读
2)自定义提取器;下面的例子显示电子邮件地址的提取器对象:
object Test {
def main(args: Array[String]) {
println ("Apply method : " + apply("Zara", ""));
println ("Unapply method : " + unapply("Zara@"));
println ("Unapply method : " + unapply("Zara Ali"));
}
// The injection method (optional)
def apply(user: String, domain: String) = {
user +"@"+ domain
}
// The extraction method (mandatory)
def unapply(str: String): Option[(String, String)] = {
val parts = str split "@"
if (parts.length == 2){
Some(parts(0), parts(1))
}else{
None
}
}
}
六:变量声明中的模式
val (x, y) = (1, 2)
val (q, r) = BigInt(10) /% 3 // 返回商和余数的对偶
val Array(first, second, _*) = arr // 将第一和第二个分别给first和second
七:for表达式中的模式
import scala.collection.JavaConversions.propertiesAsScalaMap
for ((k, v) <- System.getProperties()) // 这里使用了模式
println(k + " -> " + v)
for ((k, "") <- System.getProperties()) // 失败的匹配会被忽略,所以只打印出值为空的键
println(k)
八:样例类
abstract class Amount
// 继承了普通类的两个样例类
case class Dollar(value: Double) extends Amount
case class Currency(value: Double, unit: String) extends Amount
// 样例对象
case object Nothing extends Amount
amt match {
case Dollar(v) => "$" + v