How do (Scala 3) trait parameters interact with parameters of classes that extend the trait?
I thought I wanted to write something like this:
trait ExampleTrait(val param: Int)
case class Class(override val param: Int) extends ExampleTrait(param)
val x = (Class(1): ExampleTrait).param
However, the compiler rejects the class
line, saying:
... error overriding value param in trait ExampleTrait of type Int;
value param of type Int cannot override val parameter value param in trait ExampleTrait
I’m not clear on why that “value param of type Int cannot override val parameter value param in trait ExampleTrait”.
I tried several variations (e.g., no var
on trait parameter, no override
on class parameter, no val
on class parameter), but nothing I tried that still had the trait parameter and had a class parameter with the same name worked. (Using different parameter names worked, but they’re logically the same thing, so I want to keep the names identical.)
Of course, I can do it without trait parameters, as in:
trait ExampleTrait {
def param: Int
}
case class Class(override val param: Int) extends ExampleTrait
val x = (Class(1): ExampleTrait).param
However, I thought maybe that would be doable using trait parameters.
(No, it’s not essential that I use a trait parameter. However, I’m also trying to learn Scala 3, so I’d like to understand what’s going on and what the rules are, and whether trying use a trait parameter makes sense for my use case.)
Thanks.