user445107
user445107

Reputation:

How to generate an unique ID for an class instance in Scala?

I have a class that needs to write to a file to interface with some legacy C++ application. Since it will be instantiated several times in a concurrent manner, it is a good idea to give the file an unique name.

I could use System.currentTimemili or hashcode, but there exists the possibility of collisions. Another solution is to put a var field inside a companion object.

As an example, the code below shows one such class with the last solution, but I am not sure it is the best way to do it (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)
  }
}

Upvotes: 16

Views: 34037

Answers (2)

Gregosaurus
Gregosaurus

Reputation: 611

Did you try this :

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

See UUID javadoc, and also How unique is UUID? for a discussion of uniqueness guarantee.

Upvotes: 35

senia
senia

Reputation: 38045

it is a good idea to give the file an unique name

Since all you want is a file, not id, the best solution is to create a file with unique name, not a class with unique id.

You could use File.createTempFile:

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

Vladimir Matveev mentioned that there is a better solution in Java 7 and later - Paths.createTempFile:

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

Upvotes: 8

Related Questions