Is there a way to use `this.type` in a type parameter?

I have a situation where I want to specify that a trait I have will implement another trait. However I want the method, on the final subclasses, to work for things of the same type only. A clearer explanation is in the code snippet below:

I want the Animal trait to implement something like the Eq trait. But I also want the concrete subtypes to only be comparable with each other (Because a Dog and Cat with the same name aren’t the same, for example) .

I was able to get what I wanted working in the above example by using F-Bounded polymorphism and a self type; however it seems somewhat verbose.

I thought I could simplify things by using this.type, but it doesn’t seems to work. Doesn’t anyone know why, or if this.type can be used as an argument to a type parameter?


this.type is the singleton type of the instance, which isn’t what you want.

The way to get the constraint you want is to use a typeclass. I have a discussion here.

1 Like