Home > Back-end >  Scala Assertion unknown parameter on case class
Scala Assertion unknown parameter on case class

Time:10-31

Let's say I have the below case class that translates directly a db table and where the id will be generated randomly on the creation of a new row.

case class Test(id: UUID, name: String)

Looking at the tests right now, I need to retrieve a row from Test and compare it with

val test1 = (...., "testName")

however I don't have the first parameter since it's created randomly and I would like to ignore it somehow...

I tried doing

test1 = (_, "testName")

but it's not valid.

Is there any way where I can ignore in Scala a case class parameter ?

Thanks!

CodePudding user response:

Assuming we have

case class Test(id: UUID, name: String)

Here's a function that tests two instances of Test for equality, ignoring the id field.

def myEquality(a: Test, b: Test): Boolean =
  a == b.copy(id=a.id)

We can't explicitly tell Scala to ignore a field, but we can most certainly mock that field to be the correct value. And since these are case classes (i.e. immutable), we can't mess up any other unrelated data structures by doing this simple trick.

CodePudding user response:

To answer the question posed, the answer is no. Case class instances are defined by the values of their fields. They do not have the property of identity like normal classes. So instantiating a case class with a missing parameter is not possible.

  • Related