Created
September 6, 2024 09:12
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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