简体   繁体   中英

Dependency Injection in scala

I have a trait

trait Tt[T]{
   //tens of methods
}

and

class St{ tt: Tt[T] =>
  type T = //...
  //some methods
}

object St{
    def apply[T](tt: Tt[T]) = new St with tt //error
}

The issue is the objects of Tt are generated by a library. Is there a way to avoid implementing all these tens of methods and just "inject the instance"?

I cannot just pass it as a parameter, because of the type variable declaration that is defined inside the class.

Extracting the type variable declaration to the type parameter is not possible.

How about class St(val tt: Tt[St#T]) { type T = ... }

There is something else with your apply though: St wants the type parameter to Tt to be the same as it's own type T (you gotta start using more letters for these types), but apply is parametrized with T , which is yet another different type, that just happens to use the same letter. So, def apply[T](tt: Tt[T]) = new St(tt) won't compile, it needs to be def apply(tt: Tt(St#T)) = new St(tt)

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