I’m trying to define a clean interface for clients to use my library. Some sample client code is below.
for (security <- allSecurities) {
val askLast = ask
}
The problem is I would like “ask” to automatically be passed “security”. My attempt at doing this in the parent class is as follows
var lastSecurity = ""
private val lastAsk = new HashMap[...]
def allSecurities = for {
security <- lastTrade.keySet.toList
} yield {
lastSecurity = security
security
}
def ask = lastAsk(lastSecurity).price
Unfortunately it doesn’t quite work as I envisaged since in the client lastSecurity has the same value throughout the entire loop instead of being dynamically updated.. So basically I’m trying to allow clients to do
val askLast = ask
instead of
val askLast = ask(security)
Can I do this in Scala?
You can get what you want with a lazy “view” of the sequence,
prints
The key idea here is that with a lazy view, the
mapis not evaluated immediately, but only as elements are needed by the for loop.Here’s another approach. I’m not recommending this as good code, but it does demonstrate the flexibility of Scala,
The class
SecurityWrappercontains a customforeachmethod. In each iteration through the loop, it writes to thelastSecurityvariable. Scala’sforcomprehension sugar will automatically useSecurityWrapper.foreachwithout any extra work on our part.