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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
No comments:
Post a Comment