0

when defining a type hierarchy of case classes in 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

Would an abstract class be better suited for this purpose?

Georg Heiler
  • 16,916
  • 36
  • 162
  • 292
  • Careful, your example won't compile. The `,` in your sealed trait declaration is not legal scala. – Nicolas Rinaudo Dec 20 '17 at 12:28
  • sorry for that - fixed the sample. – Georg Heiler Dec 20 '17 at 14:04
  • There are no "already inherited parameters" in any of your cases, because `FooBar` doesn't have parameters (and traits can never have them); it has 3 methods which can be implemented as parameters or in any other way. – Alexey Romanov Dec 20 '17 at 17:13
  • 1
    If it were possible without macros someone would have suggested it as an answer to the question you've linked. – jwvh Dec 20 '17 at 17:54
  • I think the issue comes from the fact that you have to declare a signature for the constructor of your `Bar` class and the parentheses after the type name is the place in Scala where you do so (for the "main" constructor). For case classes it is also re-used as a source for declaration of fields but this is secondary. And note that unlike methods, constructors are not inherited automatically. Unless you use some tool (like a macro) to generate a constructor for you - you can't avoid the need to explicitly put its signature to the designated place. – SergGr Dec 21 '17 at 00:30

1 Answers1

1

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. Since methods without parenthesis and values are basically the same in Scala, this works.

Your second implementation calls FooBar's constructor with 3 values that don't exist. Where does it get the A from?

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.

Nicolas Rinaudo
  • 6,068
  • 28
  • 41