Constructor overloading

774 views
Skip to first unread message

ibs

unread,
Feb 12, 2012, 1:12:26 PM2/12/12
to General Dart Discussion
Why Dart doesn't allow to overload constructors. I have to define
named constructors to get some constructors with different parameter
lists.

Iph

unread,
Feb 12, 2012, 1:53:24 PM2/12/12
to General Dart Discussion
In my eyes, it looks like it would have to due with darts typing
system. Dart's typing is more for tooling, documentation, and
debugging (compile time warnings and what-not). After compiling is
said and done though, something like these functions:

function add(double a, double b);
and
function add(int a, int b);

Turn into:

function add(var a,var b);
function add(var a, var b);

Hope I am correct in saying this :)

Chris Buckett

unread,
Feb 12, 2012, 3:19:06 PM2/12/12
to General Dart Discussion
> function add(var a,var b);
> function add(var a, var b);
You are correct with that assumption.

There's a pretty good discussion of method overloading (which I guess
would also apply to constructors) on this post here:
https://groups.google.com/a/dartlang.org/group/misc/browse_thread/thread/3bfa9ef4315dd970/ac528b2772f4ebe5
It's all in the context of setStrokeColor - which happened to be the
concrete example that raised the discussion.

Hope that helps (at least in providing context),
Cheers,
Chris.

Bob Nystrom

unread,
Feb 13, 2012, 1:27:41 PM2/13/12
to ibs, General Dart Discussion
Chris and Sean answered the "why" question, I think. I'll just add that you don't always need to use named constructors. In many cases, a single primary constructor with a couple of named optional parameters will accomplish what you want.

- bob

Seth Ladd

unread,
Feb 13, 2012, 3:01:16 PM2/13/12
to Bob Nystrom, ibs, General Dart Discussion
For example:

class Dog {
  String name;
  String breed;
  int age;

  Dog(this.name, [this.breed=null, this.age=null]);
}

main() {
  var sparky = new Dog('sparky', age:2);
  print(sparky.name); // sparky
  print(sparky.age); // 2
  print(sparky.breed); // null
}

Reply all
Reply to author
Forward
0 new messages