简体   繁体   English

java.util.UUID.randomUUID 是否可复制?

[英]Is java.util.UUID.randomUUID copyable?

I have a question on whether it is possible to perform a scala case class copy (or clone) on a field defined by java.util.UUID.randomUUID .我有一个关于是否可以在java.util.UUID.randomUUID定义的字段上执行 scala case 类复制(或克隆)的问题。

Suppose I have my class set up as假设我的班级设置为

case class X(){
val id = java.util.UUID.randomUUID.toString()
}

I create an instance of X and also attempt to clone the class.我创建了一个 X 实例并尝试克隆该类。 What I noticed is that the id fields are different.我注意到的是 id 字段是不同的。 Is this expected and if so, is there a way to ensure that all copy / clone methods return the same value of id?这是预期的,如果是,有没有办法确保所有复制/克隆方法返回相同的 id 值?

val z = X()
z.id != z.copy().id

The problem is not that it is a UUID the problem is that you are misusing / misunderstanding how case classes work.问题不在于它是一个UUID ,问题在于您滥用/误解了案例类的工作方式。

The copy method of a case class is just a convenient call to the constructor of the class.案例类的copy方法只是对类的构造函数的方便调用。 So for example所以例如

final case class Foo(a: Int, b: String)

Is expanded by the compiler to something like this:由编译器扩展为如下所示:

final class Foo(val a: Int, val b: String) {
  def copy(a: Int = this.a, b: String = this.b): Foo =
    new Foo(a, b)

  // A bunch of other methods.
}

object Foo extends (Int, String) => Foo {
  override def apply(a: Int, b: String): Foo =
    new Foo(a, b)

  // A bunch of other methods.
}

So as you can see the copy is not black magic, it is just a simple method with default arguments.因此,正如您所看到的, copy不是黑魔法,它只是一个带有默认参数的简单方法。

So nothing in the body of the case class is included in the copy, so in your code the id field will be created for each instance as a call to java.util.UUID.randomUUID.toString()所以案例类的主体中没有任何内容包含在副本中,因此在您的代码中,将为每个实例创建id字段作为对java.util.UUID.randomUUID.toString()的调用

The best would be to do this:最好是这样做:

final case class X(id: String = java.util.UUID.randomUUID.toString)

This way you can omit it in creation but it will be preserved by copy .这样你可以在创建时省略它,但它会被copy保留。 You may move it at the end of the parameter list so you do not need to use named arguments always when creating it.您可以将它移动到参数列表的末尾,这样在创建它时就不需要总是使用命名参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM