如何在 Scala 中为类实例生成唯一 ID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21579725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:02:57  来源:igfitidea点击:

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

scala

提问by Gregosaurus

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.

我有一个类需要写入文件以与某些遗留 C++ 应用程序交互。由于它将以并发方式多次实例化,因此给文件一个唯一的名称是个好主意。

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

我可以使用 System.currentTimemili 或 hashcode,但存在冲突的可能性。另一种解决方案是将一个var字段放在伴随对象中。

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)
  }
}

采纳答案by senia

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.

由于您想要的只是一个文件,而不是 id,因此最好的解决方案是创建一个具有唯一名称的文件,而不是具有唯一 id 的类。

You could use File.createTempFile:

你可以使用File.createTempFile

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

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

Vladimir Matveev提到在 Java 7 及更高版本中有更好的解决方案 - Paths.createTempFile

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

回答by Gregosaurus

Did you try this :

你试过这个吗:

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

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

请参阅UUIDjavadoc,以及UUID 有多独特?讨论唯一性保证。