Understanding F-bound polymorphism in Scala

271 Views Asked by At

I'm trying to understand how it works. Here is what I tried:

abstract class TestBase { self =>
  type T >: self.type <: TestBase
}

class Test1 extends TestBase {
  type T = Test1
}

class Test2 extends Test1{
  override type T = Test1 // daaaaamn
}

The problem is if the inheritance hierarchy has length more than 2. In case of Test2 it was definitely not what I wanted. Is there a way to prevent something like that happened at compile time?

1

There are 1 best solutions below

0
On

As @Alec points out the short answer is unfortunately it appears you can't do this; however, most instances where you want to constrain types in a manner afforded by F-bounded types can be replaced with typeclasses. Rob Norris has a good discussion of F-bounded types vs typeclasses and touches briefly on the problem you're experiencing.