0

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

1
  • Not sure what your question is. What happened when you tried to use inside? - BTW, case classes MUST be immutable, as such, they shouldn't contain Arrays (in general arrays are discouraged, you shouldn't use them unless you really need them). Commented Aug 31, 2020 at 14:50

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Seq is also discouraged :p - It is better to use a concrete collection like List, Vector or ArraySeq.
Can you please elaborate why is that discouraged?
I could, but I guess Daniel does it better than me: gist.github.com/djspiewak/2ae2570c8856037a7738#problems
Arrays are mutable; it's better to use an immutable collection unless you specifically decide mutability is actually desired and necessary. And 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.
Thanks @SethTisue! I meant to ask why is it not recommended to use Seq. And the link that Luis attached was very informative.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.