本文介绍了为什么案例类只扩展 Product 而不是 Product1、Product2、...、ProductN?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我了解到 case 类扩展 Product 之后,我想知道为什么它们不扩展 ProductN.例如,给定如下代码:

after I learned that case classes extend Product, I wondered why they do not extend ProductN. E.g., given a code like:

case class Foo(a: Int)

我希望 Foo(1).asInstanceOf[Product1[Int]] 工作,但它没有(用 Scala 2.9.1 检查,并由其他来源和 产品文档).

I'd expect Foo(1).asInstanceOf[Product1[Int]] to work, but it does not (checked with Scala 2.9.1, and confirmed by other sources and by Product documentation).

我对此很感兴趣,因为我想声明这样的类:

I was interested in this, because I wanted to declare classes such as:

abstract class UnaryOp[T1 <: Exp[_], R](t1: T1) extends Exp[R] {
  this: Product1[T1] =>
}

这样,一元操作的节点必须实现Product1.如果只是一个带有一个参数的案例类就足够了,那就太好了.

This way, a node for a Unary operation must be implement Product1. It would be nice if being simply a case class with one parameter would be enough for this.

推荐答案

考虑一下:

case class X(n: Int)
case class Y(x: String, y: Int) extends X(y)

如果case类扩展了ProductN,那么会同时扩展Product1Product2,但是类型参数改变了,所以有两种不同的_1 的重载.这只是一个问题——我敢打赌还有其他问题.

If case classes extended ProductN, then that would extend both Product1 and Product2, but the type parameter changes, so there are two different overloads for _1. This is just one problem -- I bet there are others.

现在,继承案例类的案例类已被弃用,Martin Odersky 现在正在考虑让它们继承 ProductN.AFAIK,尚未完成,但障碍已消除.

Now, case class inheriting case class has been deprecated, and Martin Odersky is now considering making them inherit ProductN. AFAIK, is has not been done yet, but the obstacle has been removed.

这篇关于为什么案例类只扩展 Product 而不是 Product1、Product2、...、ProductN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-07 10:32