简体   繁体   English

Scala特征案例类和继承

[英]scala traits case classes and inheritance

when defining a type hierarchy of case classes in scala: 在scala中定义案例类的类型层次结构时:

sealed trait FooBar {
  def A:Int
  def B:Int
  def C:Int
}

// works
final case class Bar(A:Int, B:Int, C:Int)extends FooBar

// fails
final case class Bar extends FooBar(A:Int, B:Int, C:Int)

// fails
final case class Foo extends FooBar

how can I avoid to specify the already inherited parameters when defining an inherited type? 定义继承类型时,如何避免指定已经继承的参数? Is this possible without any macros: Scala case classes and constructors 没有任何宏,这是否可能: Scala case类和构造函数

Would an abstract class be better suited for this purpose? 抽象类会更适合于此目的吗?

Well, what you've declared is a trait with three abstract methods. 好吧,您已经声明的是具有三种抽象方法的特征。

Your first implementation declares a case class with 3 values that match the abstract methods declared in FooBar . 您的第一个实现声明一个具有3个值的case类,这些值与FooBar声明的抽象方法匹配。 Since methods without parenthesis and values are basically the same in Scala, this works. 由于在Scala中没有括号和值的方法基本上是相同的,因此可以使用。

Your second implementation calls FooBar 's constructor with 3 values that don't exist. 您的第二个实现使用3个不存在的值调用FooBar的构造函数。 Where does it get the A from? 它从哪里得到A

Your third implementation is declaring a concrete class that does not implement abstract methods, and cannot compile. 您的第三个实现是声明一个不实现抽象方法且无法编译的具体类。

I do not know of a (sane) solution for what you're asking. 对于您的要求,我不知道(理智的)解决方案。 You're declaring abstract methods and want to not implement them. 您在声明抽象方法,但不想实现它们。 It's probably feasible through macros, but it seems like a lot of work for not much benefit. 通过宏可能是可行的,但是似乎很多工作带来的好处并不多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM