I have a case class and am trying to test similar to this. The change would be something like this...
case class Record(names: Array[Name] ...)
I am new to Scala and not sure how this would work syntactically
I have a case class and am trying to test similar to this. The change would be something like this...
case class Record(names: Array[Name] ...)
I am new to Scala and not sure how this would work syntactically
Please consider the following code:
case class Name(first: String, middle: String, last: String)
case class Record(names: Array[Name])
val rec = Record(
Array(Name("Sally", "Anna", "Jones"), Name("Sally1", "Anna1", "Jones1"))
)
inside (rec) { case Record(nameArray) =>
inside (nameArray) { case Array(name, name1) =>
inside(name) {
case Name(first, middle, last) =>
first should be("Sally")
middle should be("Anna")
last should be("Jones")
}
inside(name1) {
case Name(first, middle, last) =>
first should be("Sally1")
middle should be("Anna1")
last should be("Jones1")
}
}
}
Note that if the number of names at case Array(name, name1) is different then the actual, the test will fail.
As Luis mentioned in the comment, it is not recommended to use Arrays in case classes. This code will work the same if you change Array into List, Vector or ArraySeq.
Array comes from the JVM directly so it has a number of peculiarities compared to other collection types. You will encounter fewer difficulties when learning Scala if you stick to normal collection types. Array never appears in normal Scala code, only in code that has a special reason to use it, usually for Java interop or when you need to squeeze out every last drop of performance.
inside? - BTW, case classes MUST be immutable, as such, they shouldn't containArrays(in general arrays are discouraged, you shouldn't use them unless you really need them).