1

I want to clone an object in scala and I am confused as to why I see an AnyRef error.

case class Foo()
case class Bar(foo: Foo)

val foo = Foo()
val bar = Bar(foo.clone())

IntelliJ says:

Type mismatch.
Required: Foo
Found: AnyRef

What am I doing wrong?

k0pernikus
  • 60,309
  • 67
  • 216
  • 347

2 Answers2

4

There are a couple of things I wan't to point out.

  1. There is no Scala clone method. This is the Java clone method which has complicated contract and there is a best practice to avoid it.

  2. Scala case classes are used to create immutable value objects. The compiler also generates code (e.g. the copy method) for making the work with such objects more convenient, but immutability is key here. The whole idea of cloning an immutable object doesn't make sense.

  3. You should use singleton objects instead of having case class without arguments.

  4. Case classes are used to model ADTs (algebraic data types) which is core concept in FP. You can take a look at Option and Either for example.

vbuhlev
  • 509
  • 2
  • 10
  • I'm using copy to change test fixtures for specific use cases so I don't have to repeat its definition multiple times and only change specific attributes. Would you recommend something else for that use case? – k0pernikus Aug 07 '19 at 22:25
  • 1
    As soon as you wan't to get a new object with modified properties, copy is perfectly fine. – vbuhlev Aug 08 '19 at 08:05
3

You most likely want to use copy:

case class Foo()
case class Bar(foo: Foo)

val foo = Foo()
val bar = Bar(foo.copy())

This works as expected. But you you are using a Java method clone instead.

k0pernikus
  • 60,309
  • 67
  • 216
  • 347