matanox
matanox

Reputation: 13686

Scala - encapsulating data in objects

Motivations

This question is about working with Lists of data in Scala, and about resorting to either tuples or class objects for holding data. Perhaps some of my assumptions are wrong, so there it goes.

My current approach

As I understand, tuples do not afford the possibility of elegantly addressing their elements beyond the provided ._1, ._2, etc. I can use them, but code will be a bit unpleasant wherever data is extracted far from the lines of code that had defined it.

Also, as I understand, a Scala Map can only use a single type declaration for its values, so it can't diversify the value type of its values except for the case of type inheritance. (to the later point, considering the use of a type hierarchy for Map values "diversity" - may seem to be very artificial unless a class hierarchy fits any "model" intuition to begin with).

So, when I need to have lists where each element contains two or more named data entities, e.g. as below one of type String and one of type List, each accessible through an intelligible name, I resort to:

case class Foo (name1: String, name2: List[String]) 
val foos: List[Foo] = ...

Then I can later access instances of the list using .name1 and .name2.

Shortcomings and problems I see here

When the list is very large, should I assume this is less performant or more memory consuming than using a tuple as the List's type? alternatively, is there a different elegant way of accomplishing struct semantics in Scala?

Upvotes: 1

Views: 112

Answers (1)

Wilfred Springer
Wilfred Springer

Reputation: 10927

In terms of performance, I don't think there is going to be any distinction between a tuple and an instance of a cases class. In fact, a tuple is an instance of a case class.

Secondly, if you're looking for another, more readable way to get the data out of the tuple, I suggest you consider pattern matching:

val (name1, name2) = ("first", List("second", "third"))

Upvotes: 2

Related Questions