How to create a unique identifier for an instance of a class in Scala?

I have a class that needs to be written to a file to interact with any inherited C ++ application. Since it will be created several times at the same time, it is a good idea to give the file a unique name.

I could use System.currentTimemili or hashcode, but there is a chance of conflict. Another solution is to place the field varinside the companion object.

As an example, the code below shows one such class with the latest solution, but I'm not sure if this is the best way to do this (at least it seems thread safe):

case class Test(id:Int, data: Seq[Double]) {
    //several methods writing files...
}

object Test {
  var counter = 0

  def new_Test(data: Seq[Double]) = {
    counter += 1
    new Test(counter, data)
  }
}
+5
source share
2 answers

a unique file name is recommended

, , , , , .

File.createTempFile:

val uniqFile = File.createTempFile("myFile", ".txt", "/home/user/my_dir")

, Java 7 - Paths.createTempFile:

val uniqPath = Paths.createTempFile(Paths.get("/home/user/my_dir"), "myFile", ".txt"),
+4

:

def uuid = java.util.UUID.randomUUID.toString

. UUID javadoc, UUID? .

+8

All Articles