Thursday, 29 December 2011

SaveAs for Strings in Scala with "Pimp my library" pattern

Problem

Have you ever wanted to save a string to a file? Well, it's one of this things you don't want to do in 3 lines of code like this:
val f = new FileWriter("some/file/name.txt")
f.write("My string I want to save")
f.close()
I would rather see it like that:
"My string I want to save".saveAs("some/file/name.txt")

Solution

Luckily in Scala we can use "pimp my library" pattern. It uses implicits to convert String to RichString containing the saveAs method:
implicit def toRichString(s:String) : RichString = new RichString(s)
class RichString(s: String){
def saveAs(fileName: String) = write(fileName, s)
private[this] def write(fileName: String, content: String) {
val f = new FileWriter(fileName)
f.write(content)
f.close()
}
}
"My string I want to save".saveAs("some/file/name.txt")
view raw gistfile1.scala hosted with ❤ by GitHub

No comments:

Post a Comment