Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional way to generate file names in Scala

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?

like image 438
KAY_YAK Avatar asked Dec 06 '22 10:12

KAY_YAK


1 Answers

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
like image 109
Jean Logeart Avatar answered Dec 25 '22 17:12

Jean Logeart