for Java Developers
About Me • C# since 2005 till 2012 • Java since 2012 • JavaScript, Dart since 2013 • Working at Farata Systems • Conduct trainings 2
What is Dart? New programming language and platform created by for Web development 3 3
Blink… � WebKit… Reader… Code Search… Chrome Frame… 4
Dart is Truly OSS • Public commits • Public issue tracker • Public code reviews • Accept contributions 5
• Dart is ECMA standard (TC52) • Also ECMA: JavaScript, C#, C++/CLI, JSON, ActionScript What does it mean? ECMA committee standardizes syntax, semantics, core libraries Why it is important? Safe to develop own VMs and embed in browsers 6
Team • Lars Bak - HotSpot, V8, a Smalltalk VM, BETA • Kasper Lund - HotSpot, V8, OOVM • Gilad Bracha - Java Specification, Strongtalk, Newspeak • Many other engineers 7
http://youtu.be/huawCRlo9H4 8
Timeline Announcement 1.3 Release Sep 1, 2011 Nov 14, 2013 Oct 10, 2011 Apr 9, 2014 First commit 1.0 Release 9
Dart at a glance • Runs in VM • Compiles to JavaScript • Dynamically typed • Object-oriented • Single inheritance • Single-threaded • Familiar sytax 10
How is it better than JS? • Faster • Predictable (no hoisting, no type coercion, etc.) • Rich standard libraries • Structured apps • Good tooling • Packaging system 11
What's Your Benefit? Q: Front-end Developer? Q: Back-end Developer? A: Build reliable apps faster A: Probably just curiosity 12
Language Tour 13
Hello World • Explicit entry point // Formal example void main(List<String> args) { print( 'Hello from Dart!' ); } // Shorter version main() => print( 'Hello from Dart!' ); 14
Built-in Types var i = 1; int var hex = 0xABCD; var d = 1.2; double var exp = 1.2e9; var s1 = 'single quotes' ; String var s2 = "double quotes" ; var b1 = false ; bool var b2 = true ; var sym1 = #mySymbol; Symbol var sym2 = const Symbol( 'mySymbol' ); List var list = [ 'item1' , 'item2' , 'item3' ]; Map var map = { 'key1' : 'val1' , 2: 'val2' , []: 'val3' }; 15
JSON is valid Dart Syntax • List and Map literals make JSON a valid Dart syntax var map = { 'firstName' : 'John' , 'lastName' : 'Doe' , 'age' : 30, 'addresses' : [ { 'street' : '' //... }, { 'street' : '' //... } ] }; 16
Optional Types Example • Best practice - explicit types for method signatures and class members, for local variables - var main () { void main () { var a = 1; int a = 1; var b = 2; int b = 2; var c = divide(a, b); double c = divide(a, b); assert(c == 0.5); assert(c == 0.5); } } � � divide (a, b) { double divide ( int a, int b) { return a / b; return a / b; } } 17
Optional Types Rules • All type annotations can be omitted • Has no effect at runtime • App without types has the same semantics • Do not cause errors, only warnings • You can always “compile” and run your program 18
Benefits of Type Annotations • Act as documentation • Advanced tools support (completion, code navigation, etc.) • Error detection via type checker • Can improve performance while compiling to JavaScript 19
Declaring Variables • null is default value for all types • Supports final and const var str1 = '' ; // type is dynamic (implicit) String str2 = '' ; // type is String Object str3 = '' ; // type is Object dynamic str4 = '' ; // type is dynamic (explicit) 20
Functions // Top-level functions void log(String message) { print(message); } // Single expression functions void log(String message) => print(message); // Nested functions void main() { void log(String msg) => print(msg); log( 'done' ); } 21
Higher-order functions // Accept function as parameter void doSomething(Function callback) { //... callback(); } doSomething(() => log( 'done' )); // Return function Function getLogger() { return (String msg) => log(msg, level: 'INFO' ); } // Assign to a variable var logger = getLogger(); logger( 'done' ); // Define function-type aliases typedef void Logger(String msg); Logger getLogger() { return (String msg) => log(msg, level: 'INFO' ); } 22
Optional Parameters Positional parameters: /// [level] parameter has default value void log(String msg, [Error error, String level = 'INFO' ]) { //... } log( 'Bad value' ); log( 'Bad value' , new ArgumentError()); log( 'Bad value' , new ArgumentError(), ‘ERROR' ); Named parameters: void log(String msg, {Error error, String level}) { //... } log( 'Bad value' ); log( 'Bad value' , level: 'ERROR' ); log( 'Bad value' , level: 'ERROR' , error: new ArgumentError()); 23
Classes 24
Class members • Declaratively defined classes and members class WampService { // Instance member WebSocket socket ; // Final member final String id ; // Static member static int buffer_size = 0; // Const member static const String URL = ‘ws://localhost/ws’ ; } 25
Getters & Setters class WampService { WebSocket _socket ; get socket => _socket != null ? _socket : _socket = new WebSocket(); set socket(WebSocket s) { if ( _socket .readyState != WebSocket.OPEN) _socket = s; else throw new StateError(); } } 26
Constructors class Person { String name ; DateTime birthday ; Person(String name, DateTime birthday) { this . name = name; this . birthday = birthday; } } 27
Automatic Assignment class Person { String name ; DateTime birthday ; Person( this . name , this . birthday ); } 28
Initializers class Person { String name ; DateTime birthday ; Person(): name = '' , birthday = new DateTime.now(); } 29
Named constructors class Collection { //... // Ordinary constructor Collection(List source) {} // Named constructor Collection.empty() {} } var c = new Collection.empty(); 30
Factory constructors • Indirect instantiation // Publicly expose abstract class abstract class Service { void doSomething(); // Expose concrete implementation via factory constructor factory Service() => new _DefaultService(); } // Internally provide concrete implementation class _DefaultService implements Service { void doSomething() {} } // You can invoke factory constructors of abstract classes var s = new Service(); 31
Factory constructors • Caching pattern class Service { static final Map<String, Service> _cache = {}; String name ; factory Service(String name) => _cache.putIfAbsent(name, () => new Service._(name)); Service._( this . name ); } 32
Java: Builder pattern public class User { // Static nested class private String firstName ; // required public static class UserBuilder { private String lastName ; // required private String firstName ; private String phone ; // optional private String lastName ; private int age ; // optional private String phone ; private int age ; � private User(UserBuilder builder) { this . firstName = builder. firstName ; public UserBuilder firstName(String firstName) { this . lastName = builder. lastName ; this . firstName = firstName; this . age = builder. age ; return this ; this . phone = builder. phone ; } } public UserBuilder lastName(String lastName) { this . lastName = lastName; public String getFirstName() { return this ; return firstName ; } } public UserBuilder age( int age) { this . age = age; public String getLastName() { return this ; return lastName ; } } public UserBuilder phone(String phone) { this . phone = phone; public int getAge() { return this ; return age ; } } public User build() { public String getPhone() { return new User( this ); return phone ; } } } // TO BE CONTINUED... } 33
Dart: a kind of “Builder pattern” class User { String firstName ; String lastName ; String phone ; int age ; // Here "this" enables type checking. User({ this . firstName , this . lastName , this . phone , this . age }); } // Usage var user = new User( firstName: 'John' , lastName: 'Doe' , phone: '+123456789' , age: 30); 34
Cascade operator // Equivalent declaration class User { String firstName ; String lastName ; String phone ; int age ; User( this . firstName , this . lastName ); } // Usage var user = new User( 'John' , 'Doe' ) .. age = 30 .. phone = '+123456789' ; 35
Automatic Fluent APIs querySelector( 'h1' ) ..text = 'Welcome!' ..classes.add( 'caption' ) ..onClick.listen((_) => print( 'clicked' )); 36
Recommend
More recommend