Search code examples
scala

Case class equals with list of byte array


I am trying to use the should matchers on a case class

case class ListOfByteArrayCaseConfig(

  @BeanProperty 
  permissions: java.util.List[Array[Byte]]

)

With the following test case

val orig = ListOfByteArrayCaseConfig(List(Array[Byte](10, 20, 30)))
val orig2 = ListOfByteArrayCaseConfig(List(Array[Byte](10, 20, 30)))

orig2 should be === orig

Obviously this would fail because the two byte arrays are not equal reference wise. What I want to do is somehow make this work without changing the test case code and still keeping the case class.

Is it even possible? (like adding a custom equals method to the case class?)


Solution

  • I found the solution. Apparently I can override the equals method in a case class

    Scala: Ignore case class field for equals/hascode?

    Though it gets rid of the reason for using case classes in the first place which is to simplify data objects.

    case class ListOfByteArrayCaseConfig(
    
      @BeanProperty 
      permissions: java.util.List[Array[Byte]]
    
    ) {
    
      override def equals(arg: Any): Boolean = {
    
        val obj = arg.asInstanceOf[ListOfByteArrayCaseConfig]
        var i: Int = 0
        for (i <- 0 until permissions.size()) {
          if (!util.Arrays.equals(permissions.get(i), obj.permissions.get(i))) {
            return false
          }
        }
        return true
      }
    }