案例类等于字节数组列表 [英] Case class equals with list of byte array
问题描述
我正在尝试在 case 类上使用 should 匹配器
I am trying to use the should matchers on a case class
case class ListOfByteArrayCaseConfig(
@BeanProperty
permissions: java.util.List[Array[Byte]]
)
使用以下测试用例
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.
有可能吗?(比如给 case 类添加一个自定义的 equals 方法?)
Is it even possible? (like adding a custom equals method to the case class?)
推荐答案
我找到了解决方案.显然我可以覆盖 case 类中的 equals 方法
I found the solution. Apparently I can override the equals method in a case class
Scala:忽略 equals/hascode 的 case 类字段?一个>
虽然它首先摆脱了使用案例类的原因,即简化数据对象.
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
}
}
这篇关于案例类等于字节数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!