2. 3 mars 2011 Sida 2 Extension Methods Whathappenshere? people.sort(#Person.lastName)
3. Extension Methods Whatwehave in Java today… Toomuchnoise! Collections.sort(people, new Comparator() { @Override public intcompare(Person x, Person y) { returnx.getLastName().compareTo(y.getLastName()); } }); 3 mars 2011 Sida 3
4. SAM types and Lambdas Single Abstract Method (SAM) 3 mars 2011 Sida 4 Thread th = new Thread(new Runnable() { public void run() { doSomeStuff(); doMoreStuff(); } }); //OLD WAY Thread th = new Thread(#(){ doSomeStuff(); doMoreStuff(); } )
5. 3 mars 2011 Sida 5 SAM and Lambdas conversion With Lambdas and SAM it looks like Collections.sort(people, #{ Person x, Person y -> x.getLastName().compareTo(y.getLastName()) }); //Old way, let’shopewesooncan @Deprecate this code Collections.sort(people, new Comparator() { @Override public intcompare(Person x, Person y) { returnx.getLastName().compareTo(y.getLastName()); } });
6. EnchancedLibraries (Collections) But it gets evenbetter with EnchancedLibraries 3 mars 2011 Sida 6 //Collections is updated. No need to specify Person x and //Person y, just say ’take a person in the [list] and sort by //last name’ (its implicit that compareToshould be used) Collections.sortBy(people, #{ Person p -> p.getLastName() });
7. TypeInference …and with somehelp from the compiler…we get TypeInference 3 mars 2011 Sida 7 //No need to specify Person, the compilercan (often) helpus //with this. Compilerintrospectpeople-list via generics Collections.sortBy(people, #{ p -> p.getLastName() });
8. MethodReference A new feature with Project Lambdas is MethodReferenceswhich gives us… 3 mars 2011 Sida 8 //Methodreferenceallowsus to ’point’ directly to the method //wewant to use in oursorting. Whyuse a particularobject? Collections.sortBy(people, #Person.getLastName );
9. Extension Methods and with Extension Methodswefinally get… 3 mars 2011 Sida 9 //Nice, wehavepeople (a List<T>) whichcandosorting. But //wait a minuteList<T> don’thave a sort(…) method… Howdid //this work? people.sortBy( #Person.getLastName);
10. Extension Methods (DefenderMethods) A way to evolve interfaces WITHOUT breakingbinarybackwardscompatability. Means that wecanadd new methods in an existing interface and the implementingclientsdoes NOT need to implement that method! A reallyneed for updatingaging Collections interface, especiallywhen lambdas and Fork-Join are introduced in Java The interface willsupply a default implementationif you do not supplyoneyourself 3 mars 2011 Sida 10
11. Enhancedlibraries Proposed Syntax 3 mars 2011 Sida 11 public interface List<T> extends Collection<T> { public intsize(); // The rest of the existing List methods extensionvoid sort(List<T> list) default Collections.<T>sort; }
12. 3 mars 2011 Sida 12 Extension Methods Questions? people.eat(#Senadin.cake)