简体   繁体   中英

Understanding F-bound polymorphism in Scala

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM