| Hi,
I just wanted to generate some more noise on the mailing list with a neat trick I (re-)discovered [1] today ;-)
I noticed my code had this recurring pattern of
val r=result doSomethingForEffectOnly r
at the end of a method, in order to return result, but first performing some effect (which does not affect result).
So, I wrote this little contraption: trait After[t]{def after(block: =>unit):t} // gotta love Smalltalk syntax ;-) def return_[t](result: t): After[t] = new After[t]{val r=result; def after(block: =>unit):t = {block; r}}
Now you can write (to give you a more concrete example than doSomethingForEffectOnly -- everything but genId is just for context):
trait Binders { private object _Binder { private var currentId = 0 private[Binders] def genId = return_(currentId) after {currentId=currentId+1} } // ... }
instead of: def genId = {val r=currentId; currentId=currentId+1; r}
I'm not entirely happy with the name "after" as you might mis-interpret genId as returning currentId+1, but for now I haven't been able to think of a better name...
Anyway, I thought this might interest someone; it certainly is a tribute to Scala's flexible syntax!
regards, adriaan
[1] This trick also used to be in scala.collection.mutable.Map (it's now deprecated) def +=(key: A): MapTo = new MapTo(key) class MapTo(key: A) { def ->(value: B): Unit = update(key, value) }
Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm for more information.
|