Why use scala's cake pattern rather than abstract fields?

前端 未结 4 830
孤街浪徒
孤街浪徒 2020-12-15 04:51

I have been reading about doing Dependency Injection in scala via the cake pattern. I think I understand it but I must have missed something because I still can\'t see the

4条回答
  •  有刺的猬
    2020-12-15 05:31

    Traits with self-type annotation is far more composable than old-fasioned beans with field injection, which you probably had in mind in your second snippet.

    Let's look how you will instansiate this trait:

    val productionTwitter = new TwitterClientComponent with TwitterUI with FSTwitterCache with TwitterConnection
    

    If you need to test this trait you probably write:

    val testTwitter = new TwitterClientComponent with TwitterUI with FSTwitterCache with MockConnection
    

    Hmm, a little DRY violation. Let's improve.

    trait TwitterSetup extends TwitterClientComponent with TwitterUI with FSTwitterCache
    val productionTwitter = new TwitterSetup with TwitterConnection
    val testTwitter = new TwitterSetup with MockConnection
    

    Furthermore if you have a dependency between services in your component (say UI depends on TwitterService) they will be resolved automatically by the compiler.

提交回复
热议问题