I really like Tie::File, which allows you to tie an array to a file’s lines. You can modify the array in any way, and when you’re done with it, you untie it, and the file’s content modifies accordingly.
I’d like to reimplement such behaviour in Scala, and this is what I have so far:
class TiedBuffer(val file:File) extends ArrayBuffer[String] {
tieFile
def untie = {
val writer = new PrintStream(new FileOutputStream(file))
this.foreach(e => writer.println(e))
writer.close
this
}
private def tieFile = this ++= scala.io.Source.fromFile(file).getLines()
}
However, the “operators” defined on the ArrayBuffer return various classes, different than my own, for example:
println((new TiedBuffer(somefile) +: "line0").getClass)
gives me a immutable.Vector. I could limit the class to a very small set of predefined methods, but I thought it would be nice if I could offer all of them ( foreach/map/… ).
What should I inherit from, or how should I approach this problem so that I have a fluid array-like interface, which allows me to modify a file’s contents?
BOUNTY: to win the bounty, can you show a working example that makes use of CanBuildFrom to accomplish this task?
The methods ending with colon are right associative so in your example you are calling
+:ofStringwith aTiedBufferas parameter. If you want to test+:fromArrayBufferyou can do:or
EDIT
I missed the point in your question, see John’s answer to return
TiedBufferobjects instead ofArrayBuffer.EDIT2
Here is an example with
CanBuildFrom. You will have to calltiemanually though to prevent the file to be tied every time the builder create a newTiedBufferinstance. There is still a lot of room for improvement, for instance++will not work but it should get you started.