Tuple and Specialization

During one of my scala interview, someone ask me :

Do you know the difference between Tuple2 and Tuple3 (or any tuple >2) ?

My simple answer was NO ? So it was time to digg around to have the answer and to share it ;)

Let see the definition of Tuple2 and Tuple3 :

final case class Tuple2[@specialized(Int, Long, Double, Char, Boolean/*, AnyRef*/) +T1, @specialized(Int, Long, Double, Char, Boolean/*, AnyRef*/) +T2](_1: T1, _2: T2)
extends Product2[T1, T2]{
...
}
final case class Tuple3[+T1, +T2, +T3](_1: T1, _2: T2, _3: T3)
extends Product3[T1, T2, T3]{
...
}

As you can see the difference here :

  • Tuple2 use these keyword @specialized to define each attributes and
  • Tuple3 use generics to define each attributes

First question come in my mind is WHY used @specialized over generics ?

@specialized has been introduced in scala 2.8, this features permits to generate classes at compile time :

Tuple2(_1: Int, _2: Int), Tuple2(_1: Int, _2: Long), Tuple2(_1: Int, _2: Double), … it will create 36 (6*6) specializations of Tuple2 at runtime

Generics in Java and the JVM, and consequently also in Scala, are implemented by using type erasure. That means that if you have an instance of a generic class, for example Tuple3[String,String,String], then the compiler will throw away the information about the type argument, so that at runtime it will look like

Tuple3[Object,Object,Object](_1: object, _2: Object, _3: Object)

The main reason to use @specialized over generics is not use boxing (int converted Int). Generics are expensive in memory space due to autoboxing

On JVM a double only takes up 8 bytes, but a Double object takes up 24 bytes

But we cannot used @specialized for Tuple3 (6*6*6 = 216 needed classes to be generate) and so on, so specialization is only available on some small subset of types (Tuple1, Tuple2, Function0, Function1, Function2, Product1, Product2, AbstractFunction0, AbstractFunction1, AbstractFunction2)

Links:

Lost in Functional paradigm

Written by

a journey of a developer which currently using scala and lots of cool stuff.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade