Reputation: 266940
I have code like this:
def begin() = {
val processor = ???
db.insert(v).map {
case Left(....) =>
case Right(...) => proccessor.do(...)
}
}
Now I want to create a partial function version so I can do this:
def begin(pf: PartialFunction[Either[CustomError, String], Boolean) = {
val processor = ???
db.insert(v).map {
pf
}
}
The problem is, the partial function pf
needs access to processor
to perform something important for this transaction.
Is it possible for the partial function to somehow gain access to this processor
val?
Upvotes: 1
Views: 44
Reputation: 22840
You can use the most basic way of dependency injection, parameters.
So instead of just receiving a PartialFunction
, you can ask for a Function
that takes a Processor
and return the PartialFunction
you want to use.
def begin(pf: Processor => PartialFunction[Either[CustomError, String], Boolean]) = {
val processor = ???
db.insert(v).map {
pf(processor)
}
}
Which can be used like this:
begin { processor =>
case Left(...) =>
case Right(...) => proccessor.do(...)
}
Another option would be to accept two handlers, one for the Right and one for the Left like this:
def begin(successHandler: (Processor, String) => Boolean)(errorHandler: CustomError => Boolean) = {
val processor = ???
db.insert(v).map {
case Right(str) => successHandler(processor, str)
case Left(error) => errorHanlder(error)
}
}
Which can be used like this:
begin {
case (processor, str) =>
proccessor.do(...)
} { error =>
...
}
Upvotes: 3