Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

Benefits of using Kotlin Java for Android

Save for later
  • 6 min read
  • 06 Mar 2017

article-image

Kotlin is a statically typed programming language for JVM, Android, and browser. Kotlin is a new programming language from JetBrains, the maker of the world’s best IDEs.

Why Kotlin?

Before we jump into the benefits of Kotlin, we need to understand how Kotlin originated and evolved. We already have many programming languages, but how has Kotlin emerged to capture programmers’ heart?

A 2013 study showed that language features matter little compared withecosystem issues when developers evaluate programming languages.

Kotlin compiles to JVM bytecode or JavaScript. It is not a language you will write a kernel in. It is of the greatest interest to people who work with Java today, although it could appeal to all programmers who use a garbage-collected runtime, including people who currently use Scala, Go, Python, Ruby, and JavaScript.

Kotlin comes from industry, not academia. It solves problems faced by working programmers and developers today. As an example, the type system helps you avoid null pointer exceptions. Research languages tend to just not have null at all, but this is of no use to people working with large codebases and APIs that do.

Kotlin costs nothing to adopt! It’s open source, but that’s not the point. It means that there’s a high quality, one-click Java to Kotlin converter tool(available in Android Studio), and a strong focus on Java binary compatibility. You can convert an existing Java project, one file at a time, and everything will still compile, even for complex programs that run up to millions of lines of code.

Kotlin programs can use all existing Java frameworks and libraries, even advanced frameworks that rely on annotation processing. The interop is seamless and does not require wrappers or adapter layers. It integrates with Maven, Gradle, and other build systems.

It is approachable and it can be learned in a few hours by simply reading the language reference. The syntax is clean and intuitive. Kotlin looks a lot like Scala, but it’s simpler. The language balances terseness and readability as well.It also enforces no particular philosophy of programming, such as overly functional or OOP styling.

Combined with the appearance of frameworks like Anko and Kovenant, this resource lightness means Kotlin has become popular among Android developers. You can read a report written by a developer at Square on their experience with Kotlin and Android.

Kotlin features

Let's summarize why it’s the right time to jump from native Java to Kotlin Java.

  • Concise: Drastically reduces the amount of boilerplate code you need to write.
  • Safe: Avoid entire classes of errors, such as null pointer exceptions.
  • Versatile: Build server-side applications, Android apps, or frontend code running in the browser.
  • Interoperable: Leverage existing frameworks and libraries of the JVM with 100% Java Interoperability.

Brief discussion

Let’s discuss a few important features in detail.

Functional programming support

Functional programming is not easy, at least in the beginning, until it becomes fun. There arezero-overhead lambdas and the ability to do mapping, folding, etc. over standard Java collections. The Kotlin type system distinguishes between mutable and immutable views over collections.

  1. Function purity

    The concept of a pure function (a function that does not have side effects) is the most important functional concept, which allows us to greatly reduce code complexity and get rid of most mutable states.

    Unlock access to the largest independent learning library in Tech for FREE!
    Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
    Renews at $19.99/month. Cancel anytime
  2. Higher-order functions

    Higher-order Functions either take functions as parameters, return functions, or both.Higher-order functions are everywhere. You just pass functions to collections to make the code easy to read.titles.map{ it.toUpperCase()}reads like plain English. Isn’t it beautiful?

  3. Immutability

    Immutability makes it easier to write, use, and reason about the code (class invariant is established once and then unchanged). The internal state of your app components will be more consistent. Kotlin enforces immutability by introducingvalkeyword as well as Kotlin collections, which are immutable by default. Once thevalor a collection is initialized, you can be sure about its validity.

Null safety

Kotlin’s type system is aimed at eliminating the danger of null references from code, also known as The Billion Dollar Mistake. One of the most common pitfalls in many programming languages, including Java, is that of accessing a member of null references, resulting in null reference exceptions. In Java, this would be the equivalent toa NullPointerException, or NPE for short.

In Kotlin, the type system distinguishes between references that can hold null (nullable references) and those that can't (non-null references).For example, a regular variable of type String can’t hold null:

var a: String = “abc”
a = null // compilation error

To allow nulls, you can declare a variable as a nullable string, written String?:

var b: String? = “abc”
b = null // ok

Anko DSL for Android

Anko DSL for Android is a great library, which significantly simplifies working with views, threads, and Android lifecycle. The GitHub description states that Anko is a “Pleasant Android application development” and it truly has proven to be so.

Removing ButterKnife dependency

In Kotlin, you can just reference your view property by its @id XML parameter;these properties would have the same name as declared in your XML file. More info can be found in official docs.

Smart casting

// Java
if (node instanceOf Tree) {
return ((Tree) node).symbol;
}
// kotlin
if (node is Tree) {
returnnode.symbol; // Smart casting, no need of casting
}
if (document is Payable &&document.pay()) { // Smart casting
println(“Payable document ${document.title} was payed for.”)
}

Kotlin uses lazy evaluation just like in Java. So, if the document were not a Payable, the second part would not be evaluated in the first place. Hence, if evaluated, Kotlin knows that the document is a Payable and uses a smart cast.

Try it now!

Like many modern languages, Kotlin has a way to try it out via your web browser. Unlike those other languages, Kotlin’s tryout site is practically a full-blown IDE that features fast autocompletion, real-time background compilation, and even online static analysis! TRY IT NOW

About the author

HariVigneshJayapalan is a Google Certified Android App developer, IDF Certified UI &UX Professional, street magician, fitness freak, technology enthusiast, and a wannabe entrepreneur.