Tuples in Dart

2,781 views
Skip to first unread message

Fernando Carvalho

unread,
Jul 28, 2012, 6:20:17 PM7/28/12
to General Dart Discussion
I would like to know if dart supports tuples, like we do in Python.
For example, I would like to create a tuple that represents a Point, so in Python, I would declare:
point_x=(1, 2)

What is the recommended way to do that in Dart?

--
Fernando

Ladislav Thon

unread,
Jul 29, 2012, 4:13:26 AM7/29/12
to Fernando Carvalho, General Dart Discussion
I would like to know if dart supports tuples, like we do in Python.

It doesn't. Dart has lists and list literals: [1, 2, 3]. Also, Dart has compile-time constants and you can make a list literal constant by prepending the const keyword: const [1, 2, 3]. Normal lists are mutable, while constant lists are not only immutable, but also canonicalized (i.e., there is always a single instance of such constant). See:

main() {
  var a = [1, 2, 3];
  var b = const [1, 2, 3];
  var c = const [1, 2, 3];

  print(a);
  a[0] = 0;
  print(a);

  print(b === c); // the === operator tests for _identity_

  // b[0] = 0; // this would fail
}

This program prints

[1, 2, 3]
[0, 2, 3]
true

 
For example, I would like to create a tuple that represents a Point, so in Python, I would declare:
point_x=(1, 2)

What is the recommended way to do that in Dart?

I'd say that the recommended way of representing a point in Dart would be

class Point {
  final num x, y;
  Point(this.x, this.y);
}

:-)

Naiem Y

unread,
Jul 29, 2012, 8:53:29 AM7/29/12
to mi...@dartlang.org
Also you can define a C# style tuple in some common library. They can be handy for passing data across private functions.

class T1<E1> { E1 item1; }
class T2<E1, E2> { E1 item1; E2 item2; }
etc...

Kevin Moore

unread,
Jul 29, 2012, 12:28:07 PM7/29/12
to General Dart Discussion
Reply all
Reply to author
Forward
0 new messages