Tuesday, August 14, 2012

Constructors in Dart

Recently I've started using the Dart language and tools to maintain my interest in programming.  Coming from a .NET and JavaScript background, many of the features of the language are familiar to me but there are also some syntactical aspects that I like and which are particular to Dart.

One of the areas within the language that I'm enjoying is the constructor syntax.

Simple and default constructors
Every class will have a default constructor which is provided in case you don't specify your own.  To specify your own constructor, simply create a method with the same name as the class.

class WordContainer
{
  List _wordList;
  
  WordContainer(List words)
  {
    _wordList = words;
  }
  
  void Print()
  {
    _wordList.forEach((word) => print(word));
  }
}

In the above example, as you might expect, we have a simple constructor which allows us to construct new instances the class by passing in a list of words:



Assignment of constructor arguments to member variables
A handy shortcut exists in the Dart language for assigning constructor arguments to member variables which can save keystrokes and time.

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

Named constructors and default parameters
Another nice feature of Dart is the named constructor syntax which is designed to make it easier to identify the purpose for different constructor overloads.  In the following example I have created a separate, named constructor which takes a single word and provides an optional parameter to specify the number of times to add the single word to the word list.  To differentiate the purpose of this constructor method, I will give it a unique name.

class WordContainer
{
  List _wordList;
  
  WordContainer.fromSingleWord(String word, [num times = 10])
  {
    _wordList = [];
    
    for(var i = 0; i < times; i++)
    {
      _wordList.add(word);
    }
  }
}

When calling the overloaded constructor method, it now becomes more readily apparent as to what is happening from where the code is called:

No comments:

Post a Comment