为什么 case 类伴随对象扩展 FunctionN? [英] Why do case class companion objects extend FunctionN?

查看:43
本文介绍了为什么 case 类伴随对象扩展 FunctionN?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你创建一个 case 类时,编译器会创建一个相应的伴随对象,其中包含一些 case 类的优点:一个 apply 工厂方法匹配主构造函数,equalshashCodecopy.

When you create a case class, the compiler creates a corresponding companion object with a few of the case class goodies: an apply factory method matching the primary constructor, equals, hashCode, and copy.

有点奇怪,这个生成的对象扩展了 FunctionN.

Somewhat oddly, this generated object extends FunctionN.

scala> case class A(a: Int)                                 
defined class A

scala> A: (Int => A)
res0: (Int) => A = <function1>

只有在以下情况下才会出现这种情况:

This is only the case if:

  • 没有手动定义的伴生对象
  • 只有一个参数列表
  • 没有类型参数
  • case 类不是抽象的.

这似乎是大约两年前添加.最新的化身是 这里.

Seems like this was added about two years ago. The latest incarnation is here.

有人用过这个吗,或者知道为什么要添加它?它使用静态转发器方法稍微增加了生成的字节码的大小,并显示在伴随对象的 #toString() 方法中:

Does anyone use this, or know why it was added? It increases the size of the generated bytecode a little with static forwarder methods, and shows up in the #toString() method of the companion objects:

scala> case class A()
defined class A

scala> A.toString
res12: java.lang.String = <function0>

更新

使用单个 apply 方法手动创建的对象不会自动被视为 FunctionN:

Manually created objects with a single apply method are not automatically considered as FunctionN:

object HasApply {
  def apply(a: Int) = 1
}
val i = HasApply(1)

// fails
//  HasApply: (Int => Int) 

推荐答案

case 类伴随对象实现 FunctionN 的原因是之前,case 类生成了一个类和一个工厂方法,而不是一个伴随对象.当我们将提取器添加到 Scala 时,将工厂方法转换为具有 apply 和 unapply 方法的完整伴随对象更有意义.但是,既然工厂方法确实符合 FunctionN,那么伴随对象也需要符合.

The reason why case class companion objects implement FunctionN is that before, case classes generated a class and a factory method, not a companion object. When we added extractors to Scala it made more sense to turn the factory method into a full companion object with apply and unapply methods. But then, since the factory method did conform to FunctionN, the companion object needed to conform, too.

也就是说,将伴生对象显示为它们自己的名称而不是函数"是有意义的

That said, it would make sense to have companion objects show as their own name, not as "function"

这篇关于为什么 case 类伴随对象扩展 FunctionN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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