As a developer when we start bootstrapping project development, we always think about some awesome Dependancy Injection (like google Guice, Spring etc.).
It will inject required object for us and will take care of object creation.
But what if compiler will to same job of dependancy injection for you instead of depending other heavy framework ?
Exactly we can achieve decency injection using implicit in scala.
Example,
Lets say we want inject UserDao into service class
It will inject required object for us and will take care of object creation.
But what if compiler will to same job of dependancy injection for you instead of depending other heavy framework ?
Exactly we can achieve decency injection using implicit in scala.
Example,
Lets say we want inject UserDao into service class
case class User(name: String, id: Int) trait UserDao { def getAll(): List[User] } class MongoUserDao extends UserDao { override def getAll(): List[User] = List.empty[User] } object UserDao { implicit val userDao: UserDao = new MongoUserDao } class UserService(implicit userDao: UserDao) { }As shown in above code, compiler will find out implicit value for userDao in its companion object.We don't need external DI framework.
No comments:
Post a Comment