简体   繁体   中英

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 .

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. What I noticed is that the id fields are different. Is this expected and if so, is there a way to ensure that all copy / clone methods return the same value of 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.

The copy method of a case class is just a convenient call to the constructor of the class. 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.

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

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 . You may move it at the end of the parameter list so you do not need to use named arguments always when creating it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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