Dependency injection using implicits

When we showed dependency injection using the cake design pattern, we also mentioned that it is possible to achieve it using implicits. The idea is that services are created in one place and then we can write methods that implicitly require what the services need. By now, you should have acquired enough knowledge to be able to get to the right solution alone, so here we will just show a subset of the big example we had previously:

case class Person(name: String, age: Int)

After we have a model defined, we can create a DatabaseService as follows:

trait DatabaseService {  def getPeople(): List[Person]}class DatabaseServiceImpl extends DatabaseService {  override def getPeople(): List[Person] = List(    Person ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.