Friday, January 20, 2012

Not So Generic

I was working on a post on Generics in Dart, had a significant amount written yesterday but was running into a couple of bugs (bug reports were, for the most part, previously submitted). Coming back today and looking at my post and trying to pick up where I left off, I decided the best option, for your sake and mine, was to delete it. I had a mess of things jumping from one topic to another, code samples that had far too much fluff and useless elements that it was far from clean, concise and illuminating. So I admitted my mind wasn't as focused as it should have been and deleted the post entirely. It wouldn't serve much purpose to try and clean it up at all.

I've decided for the time being I'm going to leave the generics to Seth Ladd's most capable post: Generics in Dart. I highly recommend reading it and pay particular attention towards the end of the post to help avoid some 'gotchas'. He does a great job explaining covariance and keeping it simple at the same time. The only additional thing I will add is that not only can you use generics on the initialization of a variable but also in the declaration as a type. Doing so will really help, particularly the editor, to keep a close eye on what you are assigning or adding to a variable. The only example I will show is very brief: http://try.dartlang.org/s/lywo
main() {
  var list1 = ["One", "Two", "Three"];
  List list2 = new List();
  List list3 = ["One", "Two", "Three"];
  
  list1.add(4); // No warning because the type isn't specifically declared.
  list2.add(4); // generates a warning
  list3.add(4); // Generates a warning
}

Assuming you are not running in checked mode, all three cases will run properly. However, list2 and list3 will generate errors on the add lines indicating that int is not assignable to a string. The first case, list1 will quietly and happily accept 4 as being added to it, even though we initially specified that the variable of Dynamic type list1 is a List of type Strings. If running in checked mode, all three will fail.

Apart from that, I decided that over the weekend I'm going to start working on an introductory tutorial to Dart. Something for the programmer with little experience. Many of the resources I've seen have been geared towards those experienced with Java programming or heavy JavaScript users. I'm debating if I should go with just VM initially and get the foundations down or just DOM initially so they can get right into results. Because lets face it, when you first start as a programmer we're all about the results and making the computer do something cool rather than all the theory and foundations. However I believe I can offer that with the VM on a starting level.

No comments:

Post a Comment