4

After reading this blog post I don't understand:

What is the difference between using self type annotations vs. specifying constructor parameters for dependency injection ?

In other words, whats the difference between this style:

object Main {
  def main(args: Array[String]) {
    val barWithFoo = new BarUsingFooAble with MyFooAble with BazAble
    println(barWithFoo.bar())
  }
}

and this:

object Main {
  def main(args: Array[String]) {
    val barWithFooAndBaz = new BarUsingFooAble(new FooAble with BazAble)
    println(barWithFooAndBaz.bar())
  }
}

and this (third option):

object Main {
  def main(args: Array[String]) {
    val barWithFoo = new BarUsingFooAble with FooAbleComponent with BazAbleComponent {
      val bazAble = new BazAble() //or any other implementation
      val fooAble = new FooAble() //or any other implementation
    }
    println(barWithFoo.bar())
  }
}

?

Is there any (beyond syntax)? (There must be, otherwise self type annotations would not exist).

EDIT:

This seems to be related question, although it does not answer this question.

This is relevant too, so basically there is no difference between the two styles at all ?

Community
  • 1
  • 1
jhegedus
  • 20,244
  • 16
  • 99
  • 167
  • The author of the article says himself: *is it better / worse than using type annotations? I would say it's a matter of style and preference, couldn't find any deeper difference*. It's a matter of flavor, there is *usually* more than one way to do something in Scala. – Yuval Itzchakov Aug 29 '16 at 16:04
  • 1
    Well, if there is no deeper difference then why is the cake pattern so important ? Why was it used in the Scala compiler ? I think there must be a deeper difference, I just don't get it yet. – jhegedus Aug 29 '16 at 16:07
  • 2
    Because it's useful and declarative. I'm assuming the writers of the Scala compiler didn't want to introduce a dependency injection library as part of the compiler dependencies, which makes sense if you think of it. Then, they'd have to inject instances themselves, using `new` and such, defeating the purpose of constructor arguments. – Yuval Itzchakov Aug 29 '16 at 16:08
  • shouldn't we treat the difference between constructor parameter and with as a `is-a` for with and a `has-a` relationship for constructor parameters? – Tomer Ben David Oct 15 '17 at 10:32

0 Answers0