Part 2 : Picking Kotlin for Android — Killing Features
Be more productive & Write expressive code & Build better architecture
Welcome to Part 2, this part is composed by a lot of gist (Java vs Kotlin sample codes) as a show case. Many useful comments/arguments are written in the gist. In order to have better reading experience, I would recommend you to use a large screen to continue to read this article.
Compile-time Null Safe
“Compile-time Null-Safe” in Kotlin is a serious and fundamental improvement compared with Java. It solves the infamous null problem in Java and gives a very productive way to write high quality and NPE-less code.
In Java, every object you created will be assigned it to null by default. It is also known as “The Billon dollar mistake”. Numerous “workarounds” has been brought out in Java, third-parties library or even in IDE, for example:
Closely look at the follow Java example, it shows four different ways to write the same functionality.
The first function
doRiskyThing is written w/o
@NotNull annotation. The function is not self-documented and you must do some workaround to improve it.
If we focus on the function declaration
public String doRiskyThing(String riskyString)without looking at the implementation details, developers won’t get any information about the input parameter. Questions may come up for Java developers :
- Can I pass a
- if I pass a
null, what will be the return?
null? empty string? other default string?
Consider if developers are required use
doRiskyThing to build something, they had to spend extra effort to run a test or look at the source code to build up their confidence.
The other two examples are the popular “Work Arounds”, ONLY
doOptionalThing(String strOpt) is safe in run-time.
In Kotlin, nullable object must be represented by appending
? . For example,
BigDecimal? . This syntax will be checked in compile time and also in IDE inspection.
No workaround is needed, and the follow functions are by-design self-documented.
As you can see the fundamental difference in this tiny example, why don’t Java fix “the billion dollar mistake”?
Java has to maintain the Backward Compatibility
So, you may ask what is the point that related to Kotlin?
In 2016 Aug, we are going use existing Java libraries to write a NEW Android application or NEW backend application. Considering the fact that both of Java & Kotlin can 100% using the existing Java libraries. If we pick Java instead of Kotlin, we have to sacrifice the beauty of compile-time Null-safe and do a lot of extra “work-arounds” in order to cope with the trade off (Backward compatibility) that we don’t even need ?
Kotlin sounds interesting? Null-Safe is only one of the major killing features.
There are at least 5+ killing features I am going to introduce.
Cautions/Disclaimer: If you keep reading the following Kotlin’s killing features, you will never want to go back to Java. Trust me, think twice before you do!
Zero Overhead Nullable Type, Nullable Chaining and Default Value
Java 8 has introduced a new
Optional<T> Class into
java.util package. As
Optional<T> is just a value type (container) to wrap a value.
However, the lack of pattern matching in Java (A very power features in Scala), unwrapping and comparing the wrapped value are damn pain in Java.
Optional<T> is proposed to be used ONLY for return type to raise the awareness of “no result”, hence, avoid NPE. Check to see the following example
Let’s see a simple example of Scala pattern matching (FYI):
Let’s see how powerful is Kotlin’s Nullable Type:
From my experience, refactoring in Java/Scala from a Type to java.util.Optional/scala.Option Type is a disaster and seems like rewriting a whole part of the affected codes. But refactoring Kotlin’s Nullable Type is nearly zero-effort.
Type inference polishes the beauty of static-typed language and can boost the coding productivity to reach as fast as dynamic-typed level.
Java and Kotlin are both static and strong typing language. This characteristic is very important to large scale application.
Good Things Come With a Price
Sometimes, the type definitions are meaningless and verbose because
- It is too obvious to Human
- The compiler should clever enough to know the type
- Type definitions increase the cost of refactoring.
For example, when we create a map with seed values with type key:
let the compiler do it for you
We can skip type definition and let the compiler make type inference for us.
The syntax is very similar to dynamic typed language but any type-mismatched operations would be considered as compilation error.
Kotlin with type inference can help us to write less-verbose code without sacrifice anything.
Default Argument & Named Argument
In a real world, there exist some situations we damn need default value instead of null. Java developers can either do a very ugly work around if-null-then-default value or do a verbose method overloading. For example,
Either the “ugly work around” and the “verbose method overloading” are also not self-documented, hard to refactor/change in Java.
Kotlin support Named and Default Argument, it helps developers to create a more intuitive, meaningful and maintainable API.
As the gist example has clearly demonstrate the power of Named and Default Argument. This is a fundamental and serious improvement in Kotlin compared with Java.
Once you get used to the Kotlin’s powerful Named and Default Argument to design your interface, you won’t go back to Java.
Extension is Awesome
In Java, we can not directly add functionalities on a
Class. If some logics applied on a specific
Type and have to be used multiple time in a project, Java developers get used to create a
Type XXX in order to follow the D.R.Y. principle.
Programming has no magic. All about Abstractions
Kotlin provided a much better abstraction to model the similar problems that are solved by “Java Utils Pattern” — Extension
Traditional Java Utils usage
How is Kotlin provided a better abstraction for this problem? We can directly add an “Extension” for a specific
“Java Utils Pattern” is not IDE-friendly, new comer won’t notice some functionalities are already implemented in the XXXUtils while Kotlin’s Extension is completely solved this problem.
Here are some screenshots to demonstrate the IDE auto-complete with the Kotlin extension.
With Kotlin extension, you would never have to ask
Is that XXXUtils.someFunc() is implemented already?
and never have to search in the .utils folder. 100% of time you will find it in the auto-completed list.
Handy Data Class
In a strongly-typed language, we will create numerous “Value Object” to hold data by a explicit type to classify their domain. For example, API Response, API Request, Data Model, Proxy Object, etc.
It is a very common practice and should be as simple as possible.
After I have met with Scala and recently with Kotlin. The only Java impression on creating a “Value Object”:
Java is too verbose and too costly to be used for Functional Programming (Immutable approach)
Start reading the following Kotlin
data class to get some insight and don’t forget to read the comment :) .
In Java, developers have to use comparatively poor way (mutable or builder pattern) to create an complex Object. For example,
How we use it in Java ?
Kotlin provides a very handy
data class that
- leverage the power of Name and Default Argument on constructor
- provide handy
.copyfor writing pure immutable object
- is developer-friendly for debugging
It helps to reduce the verbosity of getter, setter and multiple constructor. What’s more,
data class is by-default ready to be used in some popular JSON Serialization library such as GSON, Jackson.
If you are familiar with Java, without Name and Default Argument, you know that it is not feasible to create a “Value Object” that can achieve the same level of convenience as Kotlin's
data class does.
“Kotlinize” Java Library
In a large scale application, consistency is the most important role to keep source codes more predictable and maintainable.
By default, Kotlin won’t encourage to create getter/setter function for a variable. Each variable has a get()/set(value) to implement:
Therefore, in pure Kotlin code we never write
setXXX(value). But, nearly 100% of Java library would use getter/setter.
How does Kotlin solve this discrepancy? Let see the “TextView” in Java Android library.
Kotlin will Kotlinize the Java “default” getter/setter into Kotlin style, you would never feel uncomfortable to use Java libraries.
If you are experience in using Java libraries in Scala, you must damn want this features, at least I do lol.
Better Functional Programming Support
Writing functional style code in Java is comparatively much more expensive than in Kotlin. Because Kotlin provided the following features:
- Type Inference
- Inexpensive Data Class (Immutable
- Intuitive Type declaration for Functions/Lamdas, i.e.
(Int,Int) -> Boolinstead of
- Support Destructing
- Every thing is an expression (easier to write declarative code)
Major goodies (aforementioned)
- Compile-time Null Safe
- Zero Overhead Nullable Type, Nullable Chaining and Default Value
- Type Inference
- Default Argument & Named Argument
- Extension is Awesome
- Handy Data Class
- “Kotlinize” Java Library
- Better Functional Programming Support
- Intuitive String Template
- Lots of handy function are implemented in Kotlin std-lib i.e.
- Multiple class or object in single file
- Support legacy JVM. Kotlin Runs on Java 6 and its interface can have default implementation just like in Java 8.
- Best IDE Support