Slide 1

Slide 1 text

Jorge Castillo www.twitter.com/JorgeCastilloPr www.github.com/JorgeCastilloPrz [email protected] Developing Android apps with Java 8

Slide 2

Slide 2 text

About us

Slide 3

Slide 3 text

Candidates Companies

Slide 4

Slide 4 text

Our Android team Still hiring! karumi.com

Slide 5

Slide 5 text

Android N Preview recently published

Slide 6

Slide 6 text

Java 8 appeared in the spotlight

Slide 7

Slide 7 text

Two new tools added to The SDK ● Jack compiler (Java Android Compiler Kit) ● Jill (Jack Intermediate Library Linker)

Slide 8

Slide 8 text

● Compiles Java sources directly into DEX bytecode ● Improves build times (pre-dexing, incremental compilation) ● Handles shrinking, obfuscation, repackaging and multidex ● Executes annotation processors Jack dependencies { compile 'com.google.dagger:dagger:2.5' compile 'com.jakewharton:butterknife:8.1.0' annotationProcessor 'com.jakewharton:butterknife-compiler:8.1.0' annotationProcessor 'com.google.dagger:dagger-compiler:2.5' }

Slide 9

Slide 9 text

Jack Java source files Dex files Shrinking Repackaging Obfuscation Multidex Jack

Slide 10

Slide 10 text

What about libraries? (.jar, .aar, .apklib)

Slide 11

Slide 11 text

Jill Jayce Jack Extract Res ● Translate library dependencies to Jack format (.jack) ● Prepares them to be quickly merged with other .jack files Select Res Resources directory JACK used to generate a pre-dexed library Jayce Pre-dex Res .jack .class res .jar Jill (Jack Intermediate library linker)

Slide 12

Slide 12 text

APK Predexing

Slide 13

Slide 13 text

● No more .class intermediate step in toolchain: ○ Bytecode manipulation tools based on .class files (like JaCoCo) are not working anymore. ○ Lint detectors based on .class file analysis not working anymore. ● Java 8 just supported on versions >= N (API 24)* Limitations

Slide 14

Slide 14 text

Okay but, how do I use the new tools ? Let’s calm down (vamo a calmarno.)

Slide 15

Slide 15 text

● For new projects: File -> New project -> pick Android N ● For already started projects: Add this to your root build.gradle: buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.2.0-alpha4' } }

Slide 16

Slide 16 text

android { compileSdkVersion 24 buildToolsVersion "24.0.0" defaultConfig { applicationId "com.github.jorgecastillo.java8testproject" minSdkVersion 9 targetSdkVersion 24 jackOptions { enabled true } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } app build.gradle

Slide 17

Slide 17 text

Java 8

Slide 18

Slide 18 text

Supported features

Slide 19

Slide 19 text

● Default and static interface methods ● Lambdas ● Functional Interfaces ● Method references ● Repeatable annotations ● Some new reflection methods such as AnnotatedElement.getAnnotationsByType(Class) ● Streams ● Optionals minSdkVersion 24 minSdkVersion 9 ● Lambdas ● Functional Interfaces (not the ones out of the box from the JDK 8) ● Method references ● Repeatable annotations

Slide 20

Slide 20 text

Interfaces - Default methods

Slide 21

Slide 21 text

public interface DiscoverMoviesPresenter extends DiscoverMovies.Callback { default void discoverMovies(SortingOption sortingOption) { getLoadingView().showLoading(); getDiscoverMoviesUseCase().execute(sortingOption, this); } @Override default void onSuccess(List movies) { getLoadingView().hideLoading(); getMovieListView().renderMovies(movies); } @Override default void onError(String message) { getLoadingView().hideLoading(); getMovieListView().displayRenderMoviesError(message); } LoadingView getLoadingView(); MovieListView getMovieListView(); DiscoverMovies getDiscoverMoviesUseCase(); }

Slide 22

Slide 22 text

● They make Java 8 interfaces very similar to Traits or rich interfaces from other modern languages ● They allow developers to compose class behavior based on multiple interfaces ● Interfaces cannot store state Interfaces - Default methods

Slide 23

Slide 23 text

Interfaces - Static methods

Slide 24

Slide 24 text

● I would use them for utility methods tied to the contract Interfaces - Static methods

Slide 25

Slide 25 text

public interface TimeMachine { void goToTime(int hour, int minute, int seconds); void goToDate(int day, int month, int year); Long getCurrentTime(); Date getCurrentDate(); default ZonedDateTime getZonedDateTime(String zoneString) { return new ZonedDateTime(getCurrentTime(), getZoneId(zoneString)); } static Long getZoneId(String zoneString) { // ... return 10L; } }

Slide 26

Slide 26 text

Lambdas

Slide 27

Slide 27 text

● Literal representation of a function ● As in other modern languages: input args -> function body ● Assignable to variables ● Being passed as method arguments and returned as return values (High order functions) ● First class citizen ● Translated to anonymous classes for lower API versions Lambdas

Slide 28

Slide 28 text

Lambda declaration private List validMovies( List movies, Function isValid) { return movies.stream().filter(isValid::apply) .collect(Collectors.toList()); } Function isValid = movie -> movie.getId() % 2 == 0; validMovies(movies, isValid); validMovies(movies, movie -> movie.getId() % 2 == 0); (inline)

Slide 29

Slide 29 text

What if multiple args needed?

Slide 30

Slide 30 text

Functional Interfaces

Slide 31

Slide 31 text

● Provide target types for lambda expressions and method references ● Java 8 gives you some of them out of the box Functional interfaces

Slide 32

Slide 32 text

Interfaces - Static methods

Slide 33

Slide 33 text

● Custom functional interface for lambdas with 3 input arguments @FunctionalInterface public interface Function3 { R apply(A a, B b, C c); } Function3 isEven = (l, i, b) -> l % 2 == 0; ● Use it Function3 isEven2 = (l, i, b) -> { return l % 2 == 0; };

Slide 34

Slide 34 text

Method references

Slide 35

Slide 35 text

● Compact, easy-to-read lambda expressions for methods that already exist ● 4 different types Method references

Slide 36

Slide 36 text

// static method reference isValid(User::isYoung); // instance method reference isValid(user::isOld); String[] stringArray = {"Barbara", "James", "Ipolito", "Mary", "John"}; // Instance method reference of arbitrary type // (string1.compareToIgnoreCase(string2)) Arrays.sort(stringArray, String::compareToIgnoreCase); // Constructor method reference generateUsers(User::new);

Slide 37

Slide 37 text

Repeatable annotations

Slide 38

Slide 38 text

● There are some situations where you want to apply the same annotation to a declaration or type use. Repeatable annotations

Slide 39

Slide 39 text

Streams

Slide 40

Slide 40 text

● Very powerful concept available in many languages ● You can extract the stream from any collection ● flatMap(), reduce(), count(), distinct(), forEach(), max(), min(), sorted(comparator) ... Streams users.stream() .filter(user -> user.getAvatarUrl() != null) .map(User::getAvatarUrl) .findFirst() .orElse("http://anyimage.com/fallback_avatar.png"); String avatar = List users = new ArrayList<>();

Slide 41

Slide 41 text

● Jack & Jill ○ Jack documentation https://source.android.com/source/jack.html ○ More details http://android-developers.blogspot.com.es/2014/12/hello-world-meet-our-new- experimental.html ○ Annotation Processing open issue https://code.google.com/p/android/issues/detail?id=204065 ● Java 8 in Android N ○ Supported features with links to documentation http://developer.android.com/preview/j8-jack.html ○ Functional Interfaces out of the box https://docs.oracle. com/javase/8/docs/api/java/util/function/package-summary.html Bibliography

Slide 42

Slide 42 text

?