user7810882
user7810882

Reputation: 233

Destructuring custom class

I would like to destructure the following class

case class Box(name: Text, value: Text) extends Product2[Text, Text] {
    override def _1: Text = name
    override def _2: Text = value
    override def canEqual(that: Any): Boolean = ???
  }

in a for loop, like this

val boxes: List[Box] = // ...
for ((name, value) <- boxes) { /* ... */ }

I implemented the class to match implementation of Tuple2. What am I missing?

Upvotes: 0

Views: 1030

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170815

To destructure a class, you need to define an unapply method taking this class, normally in its companion object. By declaring it as a case class, this method already exists (and you can't define it manually).

But making it a case class also automatically extends Product2[Text, Text] and overrides canEqual (properly, not with ???), so you don't need these. Or _1 and _2; those are methods specifically for tuples. Leaving, as Xavier's comment says,

case class Box(name: Text, value: Text)

Upvotes: 1

pme
pme

Reputation: 14803

This works in a for-loop:

for (Box(name, value) <- boxes) { /* ... */ }

Just add Box and you have what you want

Upvotes: 1

Related Questions