Dr. Axel Rauschmayer is a freelance software engineer, blogger and educator, located in Munich, Germany. Axel is a DZone MVB and is not an employee of DZone and has posted 246 posts at DZone. You can read more from them at their website. View Full User Profile

Google's "Dart" Revealed

10.10.2011
| 15944 views |
  • submit to reddit
Today, it has finally happened: At the GOTO conference, Google has officially presented its new programming language, Dart. This post gives an overview of Dart and provides a few comments on how it fits into the current programming language landscape.

 

Information on Dart

This post is based on the following sources on Dart:


Dart in a nutshell

  • Currently, Dart is not a JavaScript replacement, but rather a “better Java” plus a next-generation GWT.
  • The language is less like JavaScript and more like an improved version of Java: reified generics, first-class functions, optional types (no type errors, just warnings), getters and setters, no primitive types.
  • It is still part of the HTML5 world and includes a DOM library.
  • There is IDE support, via an Eclipse plug-in.


An overview of the language

Functions

    // named function
    void sayGreeting(String salutation, String name) {
      final greeting = '$salutation $name';
      print(greeting);
    }
    
    // function with statement body
    window.on.click.add((event) {
      print('You clicked the window.');
    })
    
    // function with expression body
    var items = [1, 2, 3, 4, 5];
    var odd = items.filter((i) => i % 2 == 1);
    print(odd); // [1, 3, 5]

Classes

    class Point {
      Point(this.x, this.y);
      distanceTo(Point other) {
        var dx = x - other.x;
        var dy = y - other.y;
        return Math.sqrt(dx * dx + dy * dy);
      }
      var x, y;
    }

Class members:

  • Methods: see distanceTo(), above
  • Operators
        operator +(other) => new Point(x+other.x, y+other.y);
    
  • Fields
        num left, top, width, height;
    
  • Getters, setters
        num get right()           => left + width;
            set right(num value)  => left = value - width;
    
  • Constructors

    • Normal constructors
          Rectangle(this.left, this.top, this.width, this.height);
      
      Prefixing this. to parameters means that they will be automatically assigned to fields. This has been one of the proposed feature for JavaScript class literals.
    • Named constructors. Without overloading, you need a way to distinguish between alternate constructors.
          Point.zero() : x = 0, y = 0;
      
    • Factory constructors are a way to mark constructors so that no instance is produced automatically. Then you can return cached instances or instances of a subclasses.
            factory Symbol(String name) {
              if (_cache.containsKey(name)) {
                return _cache[name];
              } else {
                const symbol = new Symbol._internal(name);
                _cache[name] = symbol;
                return symbol;
              }
            }
      
            Symbol._internal(this.name);
      

Interfaces

    interface Shape {
      num perimeter();
    }
    class Rectangle implements Shape {
      final num height, width; 
      Rectangle(num this.height, num this.width); 
      num perimeter() => 2*height + 2*width;
    }


Factory classes for interfaces.
An interface can specify a factory class which can be considered to be its default implementation. One can instantiate an interface, but actually instantiates the factory class behind the scenes. The constructors of an interface delegate to the constructors of the factory class. I’m not sure how that is any different from an abstract class. It seems to cater to the fondness of interfaces that many Java programmers have.

Isolates

Erlang-style concurrency:

    // Receive messages
    class Printer extends Isolate {
      main() {
        port.receive((message, replyTo) {
          if (message == null) port.close();
          else print(message);
        });
      }
    }

    // Send messages
    main() {
      new Printer().spawn().then((port) {
        for (var message in ['Hello', 'from', 'other', 'isolate']) {
          port.send(message);  
        }
        port.send(null);
      });
    }

Quoting the language specification:

Dart code is always single threaded. There is no shared-state concurrency in Dart. Concurrency is supported via actor-like entities called isolates. An isolate is a unit of concurrency. It has its own memory and its own thread of control. Isolates communicate by message passing. No state is ever shared between isolates. Isolates are created by spawning.

Generics

Reified generics (parameterized types):

    main() {
      print(new List<String>() is List<Object>);
      print(new List<Object>() is List<String>);
      print(new List<String>() is List<int>);
      print(new List<String>() is List);
      print(new List() is List<String>);
    }
Strings
  • Triple quotes for multi-line strings
        var message = """
        Dear $user!
    
        There has been a problem!
        """;
    
  • $ for variable interpolation:
        var foo = "world";
        print("Hello $foo");
    
  • ${} for expression interpolation:
        print("Result: ${x + y}");
    

Miscellaneous features
A few interesting tidbits:

  • There is a standard library with collection classes (List, Set, Queue, Map, etc.) and a DOM API.
  • Equality is handled via the == operator and delegates to the Comparable interface (for non-null values).

Running Dart

There are several ways of running Dart code. Quoting the Technical Overview:

  • Translate Dart code to JavaScript that can run in any modern browser: Chrome, Safari 5+, and Firefox 4+ (more browser support coming shortly).
  • Execute Dart code directly in a VM on the server side.
  • Use Dartboard to write, modify, and execute small Dart programs within any browser window.

Dart is not finished yet

Upcoming features:

  • Enums
  • Possibly: a reflection API
  • Possibly: pattern matching (think: a more powerful switch for objects). Useful for isolates to better handle messages.
  • “The Dart VM is not currently integrated in Chrome but we plan to explore this option.” [source: Google Code blog]


More information on the web


Features and details
@dalmaer
:

66 folks listed as owners/commiters for Dart. Holy large team! http://code.google.com/p/dart/people/list

@pmuellr
:

Looks like Dart allows typedefs for functions, which should be nice for defining callback signatures.

Tongue in cheek

@mrspeaker:

I'll give it this, Dart certainly solves the problem of JavaScript not having anything to do with Java.

@jashkenas
:

My favorite Dart compiler class: Hack.java

@maccman
:

Dart's source contains this little gem:
static bool isVm() { return 1234567890123456789 % 2 > 0; }


How does Dart fit into the current programming language landscape?

Freely paraphrasing a tweet by @pilif:

  • If you like Java and can’t get yourself to like JavaScript, you program Dart.
  • If you like Ruby and can’t get yourself to like JavaScript, you program CoffeeScript.
  • If you like JavaScript, you program JavaScript.

What do you get compared to Java?

  • Currently, Dart is almost like GWT (which is not a bad thing): Running “natively” on a virtual machine on the server, compiled to JavaScript on the client.
  • Basing the Dart IDE on Eclipse makes sense, because you get a lot of functionality (such as Git support) for free and because it is familiar to Java programmers.
  • Dart seems like an upgrade of Java, like a cleaned up version. It even carries over some negative Java-isms, such as fields automatically becoming part of the local scope.

What do you get compared to JavaScript?

  • Main Dart killer features: optional types, actor-like concurrency via isolates. However, you can do a lot via type inference in JavaScript, class literals will come to ECMAScript.next [2] and web workers are becoming more sophisticated all the time. Dart foregoes some of JavaScript’s quirks, but then again, so does ECMAScript.next.
  • In many ways, Dart feels less versatile than JavaScript. For example, JavaScript object literals are a very powerful feature. Dart is more static and only has classes.
  • Dart seems to have decent tooling, but it’s based on Eclipse. In contrast, many JavaScript IDEs that are currently in development are based on web technologies. Writing an IDE for a language in the language itself has many advantages.
  • At the moment, Dart isn’t even faster than JavaScript on V8. Presumably, that will change in the future. But this goes to show how fast JavaScript has become and that it didn’t need static types to get there.
  • Not a JavaScript replacement? Quote from the talk:

    We are not targeting JavaScript, but rather fragmented mobile platforms.

    I’m not sure what that means. The question is: Will Dart target these platforms by compiling to JavaScript or by compiling to the native mobile environments?
  • Google could have gotten the same results by supporting ECMAScript.next [2] (plus possibly some advanced, not yet standardized features) and Traceur [3].

As things are now, we have a clean but fairly simple language without any stand-out features. For example, not even multiple inheritance via something like traits is supported. Dart’s syntax is of the familiar but generic C-style variety (Java, JavaScript, C#). As long as Chrome does not come with a built-in Dart VM, Dart feels more like a Java replacement and a next-generation GWT. Maybe it should stay that way and Google should use native Dart on servers and Android (to avoid copyright troubles) and continue to always compile it to JavaScript on web browsers. That would prevent an unpleasant fragmentation in client-side native languages. Tentative pointers in that direction are Google not yet committing to integrating the Dart VM into Chrome and saying that Dart doesn’t target JavaScript. That is a marked change in tone from the openly anti-JavaScript document that was published last year [1].

If you want to see a truly innovative language, take a look at Newspeak: Its elegant syntax is based on the well-known Smalltalk language and it has fresh new ideas regarding modularity and IDEs. Gilad Bracha, one of its creators, is part of the Dart team, which is why I expected more from that language.

References
Published at DZone with permission of Axel Rauschmayer, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

cowwoc replied on Mon, 2011/10/10 - 2:47pm

DART looks quite nice. Too bad it's tied this heavily to the web (and Javascript). I would love for Google to release a "Java 2.0" style language that runs on the JVM.

Jakob Jenkov replied on Mon, 2011/10/10 - 3:54pm in response to: cowwoc

You mean, like Scala, JRuby, Jython, Groovy etc?

Otengi Miloskov replied on Mon, 2011/10/10 - 11:34pm

To many languages and way of thinking its great but no thanks, Javascript is a standard and it gets the job done, We dont need another language that compiles to javascript(CoffeeScript, Java/GWT) or another language on top of JVM there are to many already and good ones as (Scala, Groovy, Clojure, Jython etc). Im not sure where Dart could fill the gap in this ocean of languages and tools but Im sure on one thing, it will be on a niche with Google as Google Go but the rest of the world will continue to use a standard language as javascript for long long time.

Bruno Fonzi replied on Tue, 2011/10/11 - 1:00am

I am also wondering on the real need of dart, it would have been great if Google would have contributed to haXe instead, not only it's open source but targeting way more than JS alone. http://haxe.org/doc/why

Fabrizio Giudici replied on Tue, 2011/10/11 - 7:48am

 

Comments above seems to miss the point that Google made, that is that JavaScript is supposed to be unable to scale for being used in large projects and for intrinsic limitations about the speed that a JIT can achieve. I don't know whether the two claims are true or just an excuse for Google to try to push a new product on its own. The fact that one of the two Dart authors is the guy behind V8 gives at least some hints that they know what they are talking about.

So, instead of discussing about yet another language, it would be more interesting to understand whether the two claims made by Google are true.

Artur Biesiadowski replied on Tue, 2011/10/11 - 10:01am

To paraphrase Forrest Gump movie:

Go Dart, Go.

Robin Bygrave replied on Tue, 2011/10/11 - 6:22pm in response to: Fabrizio Giudici

scale for being used in large projects and for intrinsic limitations about the speed

I'm with Fabrizio in that these are the 2 questions wrt Dart/Javascript on the client side. I image in 5 years time we will be using even more client side logic and more libraries (and dependencies between libraries) as Browsers become even more capable.

For me the important question is that of large scale client side (browser) development and whether this just gets too messy in Javascript - name spaces, choosing a prototype based inheritance approach, library dependencies etc - you have to be disciplined.

Javascript could improve in these areas of course and that is what I'm expecting/hoping.

Cheers, Rob.

Jörg Buchberger replied on Tue, 2011/10/18 - 3:42am

Not a JavaScript replacement? Quote from the talk:
We are not targeting JavaScript, but rather fragmented mobile platforms.

I’m not sure what that means. The question is: Will Dart target these platforms by compiling to JavaScript or by compiling to the native mobile environments?

Well, I'm not sure either, but that could very well mean that Dart will replace Java as source for Android apps, i.e. Dart would be compiled to Dalvik bytecode ... you can see that not only from its name Dart & Dalvik, but also from the hint "fragmented (little side blow to Oracle here?(sic!)) mobile platforms".

Javier Romay replied on Thu, 2011/10/20 - 8:29am

A multi-language site about Dart: http://www.dartexperience.com

Axel Rauschmayer replied on Thu, 2011/10/20 - 9:57am in response to: Fabrizio Giudici

@Fabrizio Giudici: Excellent point! That was the main thing I missed from the presentation: Google properly arguing their case. It is obvious that JavaScript has currently shortcomings in these areas. But ECMAScript 6 is coming along nicely!

JavaScript really may not be Dart’s target any more...

Axel Rauschmayer replied on Thu, 2011/10/20 - 9:58am in response to: Jörg Buchberger

@Jörg Buchberger: As a Java (and GWT!) replacement, Dart would make a lot of sense. With good tools, I would prefer it to Java. And it would help Google with their Java-related legal troubles.

Rehman Khan replied on Sat, 2012/02/25 - 6:13am

Hm, I really like Java and program CoffeeScript.  Uh oh!

Honestly, it comes down to this: Javascript is the worlds greatest language, until it comes time to work in Javascript.  When we can refactor a 10K, hm, 2K, how about even 50 line Javascript program in about 30 seconds without worrying about references, then people will stop trying to reinvent Javascript as something else.

Carla Brian replied on Sat, 2012/07/07 - 12:50am

This is relaly nice. You can differentiate your inventory with advanced targeting capabilities and the ability to traffic a variety of rich media campaigns with ease. - Mercy Ministries

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.