26
A BRIEF INTRODUCTION TO DART By Randal L. Schwartz <[email protected]> Version 1.3 on 10 July 2015

A brief introduction to dart

Embed Size (px)

Citation preview

A BRIEF INTRODUCTION TODART

By Randal L. Schwartz <[email protected]>Version 1.3 on 10 July 2015

OVERVIEW

Not just a "smarter javascript"TypeScriptCoffeeScriptES6

Modern languageNative VM for

development"node.js" server­side codesupporting #!/path/to/dart scripts

Transpiles efficiently to JavaScriptGreat for single page applicationsRuns in all modern browsers

DART...

is easy to learncompiles to JavaScriptruns in the client and on the serverhas great toolssupports types, without requiring themscales from small scripts to largehas a wide array of built­in librariessupports safe, simple concurrency with isolatessupports code sharingis open source

HISTORY

Founded by Lars Bak and Kasper Lund of GoogleUnveiled in October 2011Dart 1.0 released November 2013Approved as ECMA­408 standard in July 2014Dart 1.6 (deferred loading) released August 2014Dart running on Google Cloud in November 2014"Dart VM in every browser" replaced with "betterJS" in March 2015Dart 1.9 (enum and async) released March 2015On­the­fly code analysis tools released March 2015Dartpad announced May 2015First dart developer summit in April 2015Third edition of the spec published June 2015

EDITORS

Webstorm (no cost to approved students,classrooms, and open source projects)IntelliJ Community Edition (open source)Sublime Text (proprietary)Dartpad (zero install!)Eclipse (open source)Or... it's just text... use your favorite editor!

But then you miss out on the code analyzertools...

HELLO, WORLD!

Of course... the first code...

Let's introduce a variable...

That's an untyped variable... let's ensure it's astring...

main() { print("Hello, world!");}

main() { var msg = "Hello, world!"; print(msg);}

main() { String person = "World"; print("Hello, $person!");}

HELLO, PEOPLE!

Let's take it from the command line...

And refactor that into a subroutine...

main(List<String> args) { String person = "World"; if (args.length > 0) { person = args[0]; } print("Hello, $person!");}

main(List<String> args) { String person = "World"; if (args.length > 0) { person = args[0]; } sayHelloTo(person);}

sayHelloTo(String aPerson) { print("Hello, $aPerson!");}

IMPORTANT CONCEPTS

Everything is an object (inheriting from Objectclass)Typing is optional, but provides hints to the toolsTyping also provides guidance in "checked" modeCode is completely compiled before executionIncludes top­level, local, and anonymousfunctions, as well as class and instance methodsPrivacy is two level: public and private (underscoreprefix)

BUILT­IN TYPES

Numbers (int and double)String (String, UTF­16 internally)Booleans (type bool, only values are true and false)List (indexed starting at 0)Maps (indexed by objects... yes objects)Symbol (string that is identical if it is equal)

NUMBERS

Infinite precision ints in VM, normal range inJavaScriptDoubles are classic IEEE 754 standard

Converting between strings and numbers:

int a = 3;

int header_constant = 0xBABE;int large = 31415926535897932384626433832795;double pi_like = large / 1e31;main () => print(pi_like);

int three = int.parse("3");double pi_kinda = double.parse("3.14");String six_string = 6.toString();String pi_sorta = pi_kinda.toString();main () => print(pi_sorta);

BOOLEANS

Only two literals: true and falseOnly true is true. Everything else is false... unless you're in JavaScript, then it's normal JSrulesWhen developing, you can ensure properoperation before deployingIf you debug in checked mode, booleans must betrue or false

LISTS

Also known as arrays or ordered collectionsZero­based indexing (first element is item 0)In checked mode (during development), can beoptionally typed:

Includes rich set of methods: add, addAll,indexOf, removeAt, clear, sort and manymore

main () { var meats = ['cow', 'pig', 'chicken']; print(meats); print(meats[0]); meats.add('turkey'); print(meats[meats.length - 1]);

var only_numbers = <num> [3, 4, 5]; only_numbers.add('duck'); // fails in checked mode}

MAPS

Maps have keys and values, both objectsMaps are created with a literal syntax or new Map

Typing information can be added for keys andvalues:

main() { var randal = { 'name': 'Randal L. Schwartz', 'address': '123 Main Street', 'city': 'Portland, Oregon', }; print(randal['city']); randal['city'] = 'Beaverton, Oregon'; randal['zip'] = 97001;}

main() { var randal = <String,String> { ...

FUNCTIONS

Types are optional, but are checked if present andassist IDE:

Args can be positional, or named:

void sayMyName (String myName) { print("My name is $myName.");}sayMyNameToo (myName) => print("My name is $myName.");main () => sayMyName("Randal");

void sayMyName({String first, String last}) { if (last != null) { print("My name is $first $last"); } else { print("My name is $first"); }}main () { sayMyName(first: "Randal"); sayMyName(first: "Randal", last: "Schwartz");}

OPTIONAL ARGS

Required args listed first, followed by optional argsOptional args can be positional or named, but notbothOptional args can have defaults, or return nullotherwise:

void sayMyName(String first, [String last]) { if (last != null) { print("My name is $first $last"); } else { print("My name is $first"); }}void sayMyNameToo(String first, [String last = "Smith"]) { print("My name is $first $last");}main () { sayMyName("Randal", "Schwartz"); sayMyNameToo("Randal");}

OPERATORS

Rich set of operators similar to most modernlanguages15 levels of precedence, with normal usage ofparentheses to overrideInteger divide: ~/Pre and post increment and decrementType testing and casting: is, is! and asCompound assignment: a += 3Bitwise operators, like & and <<Expression if/then/else:

var $this = 3 > 4 ? "was true" : "was false";main () => print($this);

CONTROL FLOW

Generally very similar to C or JavaScriptif and elsefor loopswhile and do-while loopsswitch and caseassert (throw exception if false in checked mode)

EXCEPTIONS

Unlike Java, no need to declare types you willthrow or catchExceptions typically subclass from Error orExceptionBut you can throw any object (which is everything)Standard try, catch, finally sequence

CLASSES

Everything is an instance of a class, ultimatelyinheriting from ObjectSingle inheritance with mixinsThe new keyword can be used with a classname ora class methodObjects have members consisting of methods andinstance variablesClasses can be abstract, typically defining a mixininterfaceMany operators can be overridden to provide acustom interfaceExtend a class with the extends keyword

CLASS MEMBERS

The dot is used to refer to both methods andinstance variables:

Getters and setters can be defined for instancevariables, allowing transparent migrationClass variables and methods also supported

class Point { num x; num y;

String toString() => "Point [$x,$y]";}

main() { var point = new Point(); point.x = 4; point.y = 7; print(point);}

GENERICS

Optional types, so why use generics?Inform the compiler during checked mode, andthe IDE during development:

Can also be used for interfaces:

main() { var names = new List<String>(); names.addAll(['Randal', 'Kermit']); names.add(1e20); // fails because 1e20 is not a String}

abstract class Cache<T> { T operator [] (String key); operator []= (String key, T value);}

ASYNCHRONOUS OPERATIONS

Similar to promise libraries in JavaScriptProvides Future (one value soon) and Stream(many values over time) interfacesCan use try/catch/finally­style logic with either oftheseFor simple cases, async can be made to appearnon­async:

checkVersion() async { var version = await lookUpVersion(); if (version == expectedVersion) { // Do something. } else { // Do something else. }}

LIBRARIES

dart:core ­ numbers, collections,strings, and moredart:async ­ asyncronousprogrammingdart:math ­ math and randomdart:html ­ browser­based appsdart:io ­ I/O for command­lineappsdart:convert ­ decoding andencoding JSON, UTF­8, and moredart:mirrors ­ reflection... and many more standardlibrariesbut wait... there's even more...

PUB

Like Perl's CPAN for DartPublish shared librariesIncorporate those libraries intoyour projectThe pubspec.yaml controlsacceptable version numbersOther users can view yourdependencies when they pull downyour pubspec.yaml

REFERENCES

Many parts of this talk inspired bythese sources:

Almost everything is linked from

Dart wikipedia pageDart: Up and runningDart news

dartlang.org