Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I name a tuple (define a structure?) in Scala 2.8?

It does not look very good for me to always repeat a line-long tuple definition every time I need it. Can I just name it and use as a type name? Would be nice to name its fields also instead of using ._1, ._2 etc.

like image 458
Ivan Avatar asked Sep 10 '10 19:09

Ivan


People also ask

What is a tuple in Scala?

In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable. Tuples are especially handy for returning multiple values from a method.

Can we have variables of different types inside a tuple Scala?

Thankfully, Scala already has a built-in tuple type, which is an immutable data structure that we can use for holding up to 22 elements with different types.

Are tuples mutable Scala?

A tuple is immutable, unlike an array in scala which is mutable. An example of a tuple storing an integer, a string, and boolean value. Type of tuple is defined by, the number of the element it contains and datatype of those elements.


1 Answers

Regarding your first question, you can simply use a type alias:

type KeyValue = (Int, String)

And, of course, Scala is an object-oriented language, so regarding your second about how to specialize a tuple, the magic word is inheritance:

case class KeyValue(key: Int, value: String) extends (Int, String)(key, value)

That's it. The class doesn't even need a body.

val kvp = KeyValue(42, "Hello")
kvp._1    // => res0: Int    = 42
kvp.value // => res1: String = "Hello"

Note, however, that inheriting from case classes (which Tuple2 is), is deprecated and may be disallowed in the future. Here's the compiler warning you get for the above class definition:

warning: case class class KV has case class ancestor class Tuple2. This has been deprecated for unduly complicating both usage and implementation. You should instead use extractors for pattern matching on non-leaf nodes.

like image 126
Jörg W Mittag Avatar answered Oct 24 '22 19:10

Jörg W Mittag