案例类默认应用方法 [英] Case Class default apply method

查看:43
本文介绍了案例类默认应用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下案例类:

Assuming we have the following case class:

case class CasePerson(firstName: String)

我们还为它定义了一个伴生对象:

And we also define a companion object for it:

object CasePerson {
 def apply() = new CasePerson( "XYZ" )
}

请注意,在上面的示例中,我使用 apply 方法显式定义了一个伴随对象,而没有定义默认的 apply 方法:

Notice that in the example above I explicitly defined a companion object with an apply method, without defining the the default apply method:

// This "default" apply has the same argument as the primary constructor of the case class
def apply(firstName : String) = new CasePerson(firstName)

问: 那么 Scala 在哪里应用这个默认"?我在这里明确定义了没有默认应用的伴随对象,编译器仍然知道如何执行:

Q: So where does Scala gets this "default" apply? I explicitly defined the companion object here without the default apply and the compiler still knows how to execute this:

val casePerson = CasePerson("PQR")

这是如何工作的?

推荐答案

Case 类隐含地伴随着一个带有 apply() 的伴随对象,该对象具有与 case 的主构造函数相同的参数班级.

Case classes are implicitly accompanied with a companion object with an apply() that has the same arguments as the primary constructor of the case class.

即:

case class CasePerson(firstName: String)

将伴随

object CasePerson{
   def apply(firstName: String) = new CasePerson(firstName)
}

现在,如果您还显式定义了一个伴生对象,您可以将其视为附加到隐式定义的对象.

Now if you also explicitly define a companion object, you can think of it as appending to the implicitly defined one.

例如,在您的示例中,您向伴随对象添加了一个新的 apply:

For instance, in your example you added one new apply to the companion object:

object CasePerson{
   def apply() = new CasePerson("XYZ")
}

这个语句,你可以把它想成是在创建一个组合的伴生对象:

This statement, you can think of it as if it is creating an combined companion object:

object CasePerson{
   def apply() = new CasePerson("XYZ") // the one manually added
   def apply(firstName: String) = new CasePerson(firstName) // this one is automatically added
}

现在,如果您决定添加自己的 apply 版本,它与主构造函数具有相同的参数,那么这将掩盖案例类的默认行为.

Now, if you decide to add your own version of the apply that has the same arguments as the primary constructor, then this will overshadow the default behavior of the case class.

object CasePerson{
   def apply() = new CasePerson("XYZ")
   def apply(s: String) = Seq(new CasePerson(s), new CasePerson(s)) // will replace the default factory for the case class
}

现在,如果你调用 CasePerson("hi") 它会生成:

Now, if you call CasePerson("hi") it will instead generate:

List(CasePerson("hi"), CasePerson("hi"))

这篇关于案例类默认应用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆