Skip to content

Instantly share code, notes, and snippets.

@Sedose
Created September 6, 2024 09:12
Show Gist options
  • Save Sedose/1c2d95156a77c847034893e18a3e1a33 to your computer and use it in GitHub Desktop.
Save Sedose/1c2d95156a77c847034893e18a3e1a33 to your computer and use it in GitHub Desktop.
Scala's implicit singleton dependency injection is implemented in the language itself, rather than implicitly in a framework like in Java, or done explicitly.
// Define a trait for a generic Database Access Object
trait UserDao {
def getUser(id: Int): String
}
// Concrete implementation of UserDao
class UserDaoImpl extends UserDao {
def getUser(id: Int): String = s"User with ID $id"
}
// Implicit instance of UserDao
implicit val userDao: UserDao = new UserDaoImpl()
// Service that requires a UserDao to perform its operations
class UserService(implicit dao: UserDao) {
def getUserInfo(userId: Int): String = {
dao.getUser(userId)
}
}
@main def main(): Unit = {
val userService = new UserService()
// Usage of the service without explicitly passing the UserDao
val userInfo = userService.getUserInfo(5) // Implicitly uses the userDao
println(userInfo) // Outputs: "User with ID 5"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment