unapply
仅作匹配,不作其它输出。返回 Boolean 值
object UpperCase { def unapply(s: String): Boolean = s.toUpperCase == s } val s = "AA" s match { case x @ UpperCase() => println(x) case _ => "other" }
匹配内部数据。返回 Option[Tuple](跟 case class 类似)
object Email { def apply(user:String,domain:String) = user + "@" + domain def unapply(str:String) :Option[(String,String)] ={ val parts = str split "@" if(parts.length==2) Some(parts(0),parts(1)) else None } } private val e = Email("23", "qq.com") println(e)
unapplySeq
匹配内部数据,返回 Option[Seq]
object Domain{ def apply(parts:String *) :String = parts.reverse.mkString(".") def unapplySeq(whole:String): Option[Seq[String]] = Some(whole.split("\\.").reverse) } val Domain(p, _*) = Domain("com", "xiangzhi", "c") println(p)
正则表达式
匹配捕获组返回参数(跟 case class 类似)
val date = "(\\d{4})-(\\d{2})-(\\d{2})".r val p = "2004-01-20" match { case date(year, _*) => s"$year was a good year for PLs." } println(p)
233