Ok, I want to generate temp file names. So, I created a class with var tempFileName
and fileNo
such that it creates files like
BSirCN_0.txt
BSirCN_1.txt
BSirCN_2.txt
But, to do this I have to keep count and the way I am going it is calling next()
function of the class which returns the filename in sequence (should return BSirCN_4
in the above case. Now this goes against FP as I am modifying the state i.e. the count of names in the Object. How do I do it in a functional way. One way I can think of is keeping count where the function is called and just concatenate. Any other ways?
Just return a new object:
case class FileGenerator(tempFileName: String, fileNo: Long = 0) {
lazy val currentFileName = tempFileName + "_" + fileNo
lazy val next = FileGenerator(tempFileName, fileNo + 1)
}
You can then do:
val generator = FileGenerator("BSirCN")
val first = generator.currentFileName
val next = generator.next.currentFileName
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With