07 Scala Extractor

当object部定义了unapply方法时,该object称为extractor object。

apply通常扮演构造函数的角色:给定参数创建对象,而unapply则相反:根据对象解析出构造对象的参数

extractor常用在模式匹配和偏函数, case class默认实现了unapply方法,因此它也是一个extractor

import scala.util.Random

object CustomerID {

  def apply(name: String) = s"$name--${Random.nextLong}"

  def unapply(customerID: String): Option[String] = {
    val stringArray: Array[String] = customerID.split("--")
    if (stringArray.tail.nonEmpty) Some(stringArray.head) else None
  }
}

val customer1ID = CustomerID("Sukyoung")  // Sukyoung--23098234908
customer1ID match {
  case CustomerID(name) => println(name)  // prints Sukyoung
  case _ => println("Could not extract a CustomerID")
}

当我们调用 case CustomerID(name) => println(name) 时,就是调用了unapply方法,在IDEA中用快捷键找到方法定义时,即达到unapply方法而不是构造方法。

有时候extractor返回的参数并不是固定的,可能是一个序列,这时候就可以定义unapplySeq方法,返回 Option[Seq[T]],如Regex

case r(name, remainingFields @ _*) =>.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。