Keeping up with kotlin
“java is being forced to leave android platform by kotlin or not”
This article isn’t about java vs kotlin. We already have got plenty of good reads for that. Kotlin is a new language and it packs a great set of new features and APIs. Kotlin is superb in keeping code small and clean. Thing of matter is, we’re working on projects with almost all code in java, so we can’t transform our repos to kotlin over night what we can do is we can start building new features with kotlin and keep existing code as it is until we get some time. Meanwhile why miss all the fun that java has brought in java 8.
Adding support for java 8 APIs
Java 8 has been around for a while and we are only able to use a subset of it’s APIs with compilers or plugins like Jack and Retrolambda. With android gradle plugin 3.0 or above now we don’t need these tools. To Add java 8 support in your android studio make following changes to your projects.
- Upgrade your gradle plugin to 3.0.0 or above in project level gradle file
buildscript {
repositories {
...
// You need to add the following repository to download the
// new plugin.
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.0'
}
}
2- Android plugin 3.0.0 requires Gradle version 4.1
or higher so edit the URL in gradle-wrapper.properties
file to
distributionUrl=\
https\://services.gradle.org/distributions/gradle-4.4-all.zip
3- Update source and target compatibility to 1.8 in app level gradle file
android {
...
// Configure only for each module that uses Java 8
// language features (either in its source code or
// through dependencies).
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
And make sure to remove any other java 8 compilers or plugins you have been using before like jack Compiler and Retrolambda.
Why? If Android Studio detects that your project is using Jack, Retrolambda, or DexGuard, the IDE uses Java 8 support provided by those tools instead. However, consider migrating to the default toolchain.
Setup is never that easy so if you get this error
Error:All flavors must now belong to a named flavor dimension.
The flavor 'flavor_name' is not assigned to a flavor dimension.
then add a product flavor dimension in each of your product flavours for ex:
flavorDimensions "default"
productFlavors {
dev {
dimension "default"
}
prod {
dimension "default"
}
}
For any other issues check here
One more thing android gradle plugin 3.0.0 or above requires buildToolsVersion ‘26.0.0’
which BTW has become optional from v3.0.0. Below are the APIs that we can use after this.
These are compatible withminSdkVersions
- Lambda
- Method references
- Try with resource
- Default and static interfaces methods
- Type and repeating annotations
and these APIs are currently supported in SDK version > 24
java.lang.annotation.Repeatable
.AnnotatedElement.getAnnotationsByType(Class)
java.util.
java.lang.FunctionalInterface
java.lang.reflect.Method.isDefault()
java.util.function
To see how to use these APIs, check here
Note:If you’re experiencing issues related to the support for Java 8 language features, you can disable it by adding the following to your gradle.properties file.
android.enableDesugar=false
Optional in Android
NullPointerException Of all the problems a missing null check can ruin the moment and because of that it has become a habit of most programmers to add null check before accessing anything. In Tony Hoare’s words, He calls it “my billion-dollar mistake”.
Optional is java’s solution for the NullPointerException. By Definition it is
“A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value”.
Optional unfortunately isn’t back ported for earlier android versions so we will have to use some third party libraries like these.
An example of Optional isPresent() and get() API. Here we have wrapped our car object using Optional and now we can use isPresent to check if value exists and get to access the present value and if value is nullOptional.ofNullable
returns Optional.empty()
Optional<Car> carOptional = Optional.ofNullable(carObject);
if (carOptional.isPresent()) {
System.out.println(carOptional.get());
}
Previously same was achived like this
Car car = ..//car object initialisation
if(car != null) {
System.out.println(car);
}
But there is more to Optional class so check this git repo.
Note from Oracle: The purpose of Optional
is not to replace every single null reference in your codebase but rather to help design better APIs in which—just by reading the signature of a method—users can tell whether to expect an optional value. In addition, Optional
forces you to actively unwrap an Optional
to deal with the absence of a value; as a result, you protect your code against unintended null pointer exceptions.
Lombok
Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java. Never write another getter or equals method again. It uses annotations to generate boilerplate code for you.
To give a preview
public class Student {
int id;
String name, branch;
public Student(int id, String name, String branch) {
this.id = id;
this.name = name;
this.branch = branch;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
//override equals, hashCode,toString
}
With Lombok same class will look like this
import lombok.Data;@Data
public class Student {
private int id;
private String name, branch;
}
Check this link for Lombok setup instruction in android and this for feature-list
So for the sake of keeping up with kotlin we got
- Optional for null safety
- We got Lambda expressions for code reduction and inline method calls
- We already have Butterknife for accessing views without findviewById
- And like Data class in kotlin we got Lombok
- And there is plenty of new java 8 APIs which’ll be available soon
Conclusion
Java is adding more and more with new releases and providing for it’s drawbacks with newer APIs. We may not be required to look elsewhere if it can keep up. Cheers!!!
Thanks for reading this article. Be sure to click ❤ below to recommend this article if you found it helpful. Happy Learning :)
Check all the top articles at blog.mindorks.com
Also let’s connect on facebook, twitter, github and linkedin.