假设一个基本的案例类,如
case class Natural(i: Int)
哪个是
class Natural(val i: Int)
object Natural {
def apply(i: Int): Natural = new Natural(i)
def unapply(n: Natural): Option[Int] = Some(n.i)
}
但我也有
def xxxx(i: Int): Option[Natural] = if (i > 0) Some(Natural(i)) else None
类似于 unapply ,但具有反向参数(例如 apply )。另一个例子:
class HttpMethod(val name: String)
object HttpMethod {
def apply(name: String): HttpMethod = new HttpMethod(name)
def unapply(method: HttpMethod): Option[String] = Some(method.name)
def xxxx(name: String): Option[HttpMethod] = name.toUpperCase match {
case "GET" => Some(HttpMethod("GET"))
case "PUT" => Some(HttpMethod("PUT"))
...
case _ => None
}
}
是否有 xxxx 名称的约定?我认为来自,但它也可能是一个重载的 unapply 。如果是后者你可以做
val methodString: String = ???
methodString match {
case m @ HttpMethod(name) => // use m...
}
(如果有效,可能会因为超载而失败)。但请注意,这不是一个提取器,但是像构造函数一样,因为它说:如果这个字符串可以是一个Http方法,那么构建它并... 真正的提取器是
val method: HttpMethod = ???
method match {
case HttpMethod(name) => // and now you have extracted the string name.
}
当然它在具有密封特性的GADT中更有意义,但问题不在于此,而是关于 xxxx的惯例