I’m trying to use Scala as part of an existing Java application and now I run into an issue with dependencies injected with a setter method (no DI frameworks in this part of code). How is this handled in a Scala way?
In Scala both val and var require to be initialized when declared but I can’t do that, since the Java setters inject objects that implement a certain interface and interfaces are abstract and can not be instantiated.
class ScalaLogic {
var service // How to initialize?
def setService (srv: OutputService) = {
service = srv
}
Is there a way to initialize the var service so that I can later assign a dependency into it? It should be lexically scoped to be visible in the whole class.
Try using class
Option. This is the moral equivalent of usingnullin Java. Declare the service like so:and use
or pattern matching