Small article about Scala, tuples

bearophile bearophileHUGS at lycos.com
Sun Jun 12 16:50:00 PDT 2011


A small intro to basic Scala programming, it shows nothing of the advanced Scala features. It seems Scala too use Python-style tuples:
http://www.artima.com/weblogs/viewpost.jsp?thread=328540


I've created a small test of Scala tuples:
http://ideone.com/9wrJc


object Main {
  def main(args: Array[String]) {
    val t2 = (1, 2)
    println(t2) // (1,2)

    // It's just syntax sugar for:
    val t2b = new Tuple2(1, 2)
    println(t2 == t2b) // true

    val t3 = (1, 2, 3)
    println(t3) // (1,2,3)

    // unpacking syntax:
    val (x, _) = t2
    println(x) // 1

    // alternative tuple literal syntax:
    val t2c = 1 -> 2
    println(t2 == t2c) // true

    // the alternative tuple syntax allows to
    // define maps as not built-ins:
    val d = Map(1->2, 3->4)
    println(d) // Map(1 -> 2, 3 -> 4)

    // The single item "tuple" seems to not have literal sugar:
    val t1 = Tuple1(1)
    println(t1) // (1)
    //val t1b = (1,) // syntax error
    val t1c = (1)
    val i = 1
    println(t1c == 1) // true
  }
}


Output:

(1,2)
true
(1,2,3)
1
true
Map(1 -> 2, 3 -> 4)
(1)
true


The tuple literals when printed don't show the types of the single items, I think it's better for D tuples to do the same, despite the little loss of precision, because they become more readable.

In D tuples are useful in other situations too:

forach ((a, b); zip([1,2,3], "abc")) {...


auto t2 = tuple(1, 100);
switch (t2) {
  case tuple(1, _):
  default:
}

Bye,
bearophile


More information about the Digitalmars-d mailing list