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.