0

I am new to Scala and now I went through a construct like the following:

scala> var a = List(('a',1),('b',2))   

I googled this one and it turned out to be a Scala tuple2. My question is:

Is this a special Scala constructs i.e whenever I use ('a',3), scala creates a Tuple2 or there is something configured that I can change to make scala create MyTuple2 instead of Tuple2? Can I create my own class that makes scala use it whenever I use its constructor?

Adelin
  • 18,144
  • 26
  • 115
  • 175
  • 5
    Technically speaking, `Tuple2` is a class like any other, You can create your own. However, the fact that `(a, b)` creates one, is sugar syntax that is defined inside the compiler, I believe it is even defined in the grammar of the language. So you can not make it work for your own tuple. Tuples are a primitive of the language _(like an `Int`, for example)_ it is hard to reproduce those very fundamental things, they are tied deep down on the language itself. – Luis Miguel Mejía Suárez Sep 23 '19 at 10:12
  • @LuisMiguelMejíaSuárez makes sense, can you add this as a question? I think it answers my questions – Adelin Sep 23 '19 at 10:13

1 Answers1

0

As pointed out in the comments, Tuple2 is just a class like any other. You can create your own like this:

case class MyTuple2[A, B](a: A, b: B)

val myTuples: List[MyTuple2[String, Int]] = List(MyTuple2("a", 1), MyTuple2("b", 2))

As for the syntax, you cannot override the syntax-sugar of normal tuples (afaik). There are certainly things you could do with implicits or macros to fake it, but I'd strongly encourage you not to do that as it's highly surprising to anyone else if something looks like a standard Tuple2, but doesn't behave like one.

felixbr
  • 843
  • 1
  • 7
  • 18