在 Scala 中应用和取消应用构造函数 [英] Is apply and unapply a constructor in scala
问题描述
在 Java 中,我们可以使用类名创建构造函数.但是在 Scala 中,我看到了 apply 和 unapply 的不同用法.这和Java中构造函数的用法一样,可以使用apply和unapply作为构造函数吗?
In Java we can make a constructor using the class name. But in scala I have seen different uses of apply and unapply. Is this the same like the usage of a constructor in Java, in which we can use apply and unapply as a constructor?
推荐答案
apply()
可以用作工厂方法(而不是构造函数),它通常是,但不受限制或必须如此.apply()
的特殊之处在于它可以被悄悄地"调用.
apply()
can be used as factory method (not a constructor), and it often is, but it is not restricted or required to be so. What makes apply()
special is just that it can be "silently" invoked.
class MyClass(arg: String) {
def apply(n: Int):String = arg*n
}
val mc = new MyClass("blah")
mc.apply(2) // res0: String = blahblah
mc(3) // res1: String = blahblahblah
您经常会看到 apply()
在伴随对象中用作工厂方法.
You'll often see apply()
used as a factory method in a companion object.
object MyClass {
def apply(s: String): MyClass = new MyClass(s)
}
val mc = MyClass("bliss") // call the object's apply() method
但是,同样,这只是一个方便的约定,而不是要求.
But, again, that's just a convenient convention, not a requirement.
unapply()
(和 unapplySeq()
)的不同之处在于,每当您尝试在类实例上进行模式匹配时,它都会静默"调用.
unapply()
(and unapplySeq()
) is different in that it is "silently" called whenever you attempt to pattern match on a class instance.
class MyClass(val arg: String) {}
object MyClass {
def unapply(x: MyClass): Option[String] = Some(x.arg)
}
val mc = new MyClass("bland")
mc match {
case MyClass(s) => println(s"got $s") // output: "got bland"
case _ => println("not")
}
这篇关于在 Scala 中应用和取消应用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!