Problem
Managing opening and closing multiple resource automatically. For example when you want to copy a file you need to open and close both input and output files.Solution
I recently came across scala-arm library written by Josh Suereth. I liked the idea so much that I wanted to experiment with writing something similar, but a bit simpler myself.Here is what I came up with:
Explanation
The magic is in the foreach method and the way the for and map work. They both use the foreach method. We are using this fact and wrapping the iteration with try-finally block, so we can call the close or dispose method when the traversal is finished.The rest of the magic are just implicit conversions between anything which contains def close() : Any or def dispose() : Any and Managed trait.
Enjoy!
No comments:
Post a Comment