Saturday, October 15, 2011

Google's new programming language: Dart

This week Google released details of Dart their new programming language for building web applications.  According to its creators the goal of Dart is not to be a replacement to good all JavaScritpt, but rather to offer a more modern alternative.  A Dart compiler will be going into Chrome later this year and for those browsers that do not support it, there is an option to compile Dart code to plain JavaScript.  It seems to me that Dart is meant to be more like a JavaScirpt killer in the long run... only time will tell that.  Ok enough of this, and let's get to some Dart code. Dart's syntax is very java-like, c#-like so having any familiarity with these two will easily help you understand what's going on. 

interface Shape {  
    num Area( );  
}  
   
class Rectangle implements Shape {  
    
    // The "_" undercore before field names makes them private  
    num  _height;   
    num  _width;  
    
    // Short form for boilerplate constructor  
    Rectangle(num this._height, num this._width);   
    
    num Area( ) =>  _height * _width;  
   
    // Getters and setters can be define "similar" to property fields   
    get width( ) = > _width;  
    set width(num value) {  
        if (value < 0)  
            throw "The width cannot be negative. ";  
        _width = value;  
    }  
    
    get height( ) => _height;  
    set height(num value) {  
        if (value < 0)   
            throw "The height cannot be negative. ";  
        _height = height;  
    }  
}  
   
main( ) {  
    // var rectangle = ... is ok too  
    Rectangle rectangle = new Rectangle(4, 5);  


    // Accesing getters settles: there is no visible difference   
    // between this and the "real" class fields  
    print("Rectangle, height: " + rectangle.height + " width: " + rectangle.width);  
    print("Rectangle, area is: " + rectangle.Area());  
    
    rectangle.width = - 2;  
 }   
-----------------------------------------------  Output  -----------------------------------------------

I have placed comments in the example above for some of the things that I think are kind of neat. There are a lot of interesting features like Generics, Isolates, and Factory classes for interfaces that I'll have to explore next.  Dart is not finished yet: enums and a reflection API are just some of the upcoming features.  Anyway, weather if not Dart "takes over the world",  I'll be giving it a fair change... just like I did to other languages.  

No comments:

Post a Comment