Gary LO

@gaplotech

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:

  • @NotNull
  • Objects.requireNonNull(..)
  • Optional.ofNullable(..)

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 null?
  • 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,Int? String? Long? DateTime? 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

Java Optional Overheads example

Let’s see a simple example of Scala pattern matching (FYI):

Scala Option pattern matching

Let’s see how powerful is Kotlin’s Nullable Type:

Kotlin 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

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

In Java, compared with dynamic and weak typing language like PHP or Javascript, you have to spend extra effort to specify the type definition for variables.

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: String value: Integer

In Kotlin,

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 XXXUtils for 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 Type with a very simple syntax! (Very similar to javascript)

“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 .copy for 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 writegetXXX() or 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.

Standard Android TextView(Java) in Kotlin

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 .copy features)
  • Intuitive Type declaration for Functions/Lamdas, i.e.(Int)-> Int , (Int,Int) -> Bool instead of java.util.functions.BiFunction<T,U,R>...
  • Support Destructing
  • Every thing is an expression (easier to write declarative code)
Easy to create Pair & destructing a pair
Destructing a List
Destructing a data class
Currying function example
Every thing is an expression

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

Minor goodies

  • Intuitive String Template
  • Lots of handy function are implemented in Kotlin std-lib i.e. array.find …
  • 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
Hacker Noon is how hackers start their afternoons. We’re a part of the @AMI family. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!
Topics of interest

More Related Stories