简体   繁体   中英

Share generic between traits

I have two traits

trait Base[A]

trait SometimesUsedWithBase[A] {
    this: Base[A] =>
}

I then use these with a class

class StringThing extends Base[String] with SometimesUsedWithBase[String]

It would be great if I didn't have to define SometimesUsedWithBase 's type, and instead it somehow understands that it's using the type defined in Base so that it looks like:

class StringThing extends Base[String] with SometimesUsedWithBase

Is this possible?

You should be able to do something like this.

trait Base[A] {
  type BaseType = A
}

trait SometimesUsedWithBase {
  this: Base[_] =>
  def someFunction: BaseType
}

class StringThing extends Base[String] with SometimesUsedWithBase {
  def someFunction: String = ""
}

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