10 Features of Kotlin for Android Developers That Will Tempt You to Use It

1558 Views
|
18 Sep 2017
|
8 min
author avatar
Vitaly K.
Copywriter

Kotlin language originally appeared in 2011 and has made quite a stir since then. It went from a new language with blurry perspectives to the Kotlin version that’s approved by Google and known as the formal language supporting Android development.

If you're here to learn the main Kotlin features which help it gain popularity, as well as learn about its story along with how to get started with it on your Android Studio -- you're at the right place!

What is Kotlin and does it have a future?

Kotlin is the object-oriented language created by the guys from JetBrains. Yeah, the same company that developed the famous IDE which by the way served as a basis for Android Studio -- the official tool for developers built in Google.

It works on the JVM just as Java. That makes Kotlin programming language suitable for building apps for Android. Certainly Android doesn't use the JVM exactly, but still, its roots with Java are strong. That's why the fact that the language is interoperable with Java has played into Kotlin's hands, making it a choice of hundreds of thousands of developers worldwide.

Kotlin language: Popularity on GitHub

GitHub features Kotlin in its list of actively developing languages (Source: GitHub)

Google announced the support of Kotlin for Android at its annual conference called Google I/O that was held in May 2017. It is a huge step forward for this language since it allows Kotlin to interact with Android in a more natural way. By the way, tools for Kotlin will be added by default starting with Android Studio 3.0 that is currently in beta.

Even though it has a bunch of things in common with Java it differs through some agreeable features like clean Kotlin syntax, along with ideas focused on functional programming and a lot of other improvements over Java.

If compared to Swift language for iOS development, Kotlin isn't the internal project of Google, so it won't belong to the company. However, JetBrains says they're intended to continue developing and supporting this project. They are already cooperating with Google to create a foundation facilitating learning Kotlin language and straightening its positions. Besides, creators want to continue working on the language and tailor it better for other platforms.

As we can see, two powerful companies at once are pushing this language forward and that doesn't make its future seems as blurry as it used to be at the very beginning.

Features of Kotlin

Solutions for Android in Kotlin are becoming more and more popular. Let's take a look at some prominent features for which Kotlin has already got an army of admirers.

1. Full compatibility with Java

Being initially designed to replace Java, Kotlin is capable of Java classes inheritance, implementing its interfaces, calling its methods, and much more. In turn, Java is capable of Kotlin classes inheritance, implementing the Kotlin interface and calling its methods.

Things are getting even better in case you prefer using IntelliJ IDEA built by JetBrains. This software is able to convert a Java-written code into Kotlin. Everything you need to do is to copy your Java-based code, create a Kotlin file, and paste the copied code there. Thereafter, IntelliJ will propose you to translate this code into Kotlin language for you. Of course, this translation feature isn't ideal, but, nevertheless the places of its failures lead to compile errors.

2. Extension Functions

As its name suggests these Kotlin programming functions are intended to help you in extending the classes functionality without touching their code.

class User {
  var firstName = ...
  var lastName = ...
}

// Probably the author of the User class forgot to include this
fun User.setName(firstName: String, lastName: String) {
  this.firstName = firstName
  this.lastName = lastName
}

That's extremely useful in case you're dealing with tons of library code that can't be changed, while you still have an opportunity to keep your actual classes in a miniature and easy-to-understand format. The function cannot access any class' private fields. That's why it won't breach invariants of an author that he or she kept in mind creating a certain piece of code.

It must be noted that you shouldn't overdo it with these methods in case your IDE isn't good enough. In another case, you can be faced with some difficulties when trying to find where all of them come from. If it is possible -- store them in the file with the class.

3. High-Order Functions

This function is intended to take functions as parameters or return a function. Kotlin language allows you to declare functions of a higher order functioning on a distinct type. Puzzled? Let's take a look at this example:

fun shape(init: Shape.() -> Unit): Table {
  val shape = Shape()
  shape.init()
  return shape
}

fun Shape.line(init: Line.() -> Unit) {
  val line= Line()
  line.init()
  this.add(line)
}

fun Shape.textCell(text: String) {
  this.add(TextCell(text))
}

4. Inline Functions

It may seem that these high-order constructions will cost you a priceless runtime. In order to avoid such a situation, you should inline them.

Kotlin coding language provides you with the opportunity to totally manage the function inlining. Everything you need to do is to note a certain function as inline and that's it. Let's take a look at this Kotlin code:

fun findVip(users: List<User>): User? {
  users.forEach {
    if (user.isVip) {
      return user // Returns from findVip, not just from the lambda
    }

  }  return null
}

5. Null Safety

With the help of ?. operator in Kotlin, you can avoid lots of problems connected with the NullPointerExceptions. It checks whether the value is null or not and in case it is not null -- the next action will be performed, for instance:

val text:String = "name"
text = null // As text is defined as null save it will show error
text.length

In Kotlin, all the objects by default are null safe, so the null will not be accepted for the value. Though, there are some scenarios when the null can be the value. In this case, you should define them by means of ? according to Kotlin syntax. Let's say:

val text:String? = "name"
text = null
text.length //This will show error as ?. is not used may result in NPE.
text?.length //This is completely valid now.
text!!.length //This will produce NPE if text is null.

6. Apply function

It acts as a method for any object. Here's this function of Kotlin in action:

val john = User().apply {
  firstName = "John"
  lastName = "Dow"
  age = 25
}

The good thing is that the return value of this function in Kotlin is actually the object it was called on. That fact makes the usage of apply really convenient especially when it comes to huge expressions. With its help, you aren't obliged to create excessive auxiliary variables.

7. Express your code easily

In contrary to Java, Kotlin language has no conditional expression. However, it compensates its lack with the help of if expression. Here is how it looks in Java: 

val age =
    person == kate? 18 : person.age

That's how it looks in Kotlin:

val age =
    if (person == kate) 18 else person.age

It might not seem to be one of the Kotlin advantages at first glance, but the practice of Ruby shows that's the right way to get compact and readable code. Just look at this:

// No more need to declare it outside the try block, then
// assign inside!
val file = try {
  FileInputStream(...)
} catch (e: IOException) {
  Log.e(e)
  throw e
}

// "when" is like "switch" but with a different name
// (and no fallthrough).
val name = when (char) {
  'm' -> "Max"
  'a' -> "Andreas"
  'd' -> "Derek"
  else -> "No one"
}

8. Functions with sole expression

When it comes to short functions, you are able to take advantage of Kotlin's syntax like this:

fun fullName() = firstName + " " + lastName

That's also very suitable in case you need to add some plain extension methods.

9. Set free your variables & functions

Java demands everything to be fitted in a class. Even if it's not connected to any class function -- you are still obligated to make a static method of a class from it. Talking about Kotlin, it is enough just to define functions, variables or objects at the top level of your file. This way, you are no longer in need of the pattern called Singleton:

val singleton = object {
  ...
}

10. Kotlin and Algebraic Data Types

In fact, Kotlin language allows you to define full-scale algebraic data types with the help of sealed class that's similar to the final class in Java. Take a look at this classical example with the link list:

sealed class Type {
  class NoType : Typet()
  class StandardType(val value: Int) : Type()
}

In this particular example, sealed implies that only classes that are nested have an opportunity for inheriting from it. In turn, that guarantees to other code the impossibility of other values (except for Nil/Cons). Compiler understands that:

fun handle(type: Type): Int = when (type) {
    is Type.StandardType -> type.value
    // Compile error! Forgot to handle the NoType case.
}

Talking about the application of this scenario of Kotlin in action, it may come in handy for state machines with the states transferring a certain amount of data that is useless for other states.

sealed class State {
  class SettingUp() : State()
  class Drawing(val x: Position, val y: Position) : State()
  class DrawingOver() : State()
}

Setting up Android Studio for Kotlin

As I already mentioned, Kotlin will be added to Android Studio 3.0 which is currently in beta. Nevertheless, if you can't wait to build mobile apps on Android with Kotlin and don't want to use any beta versions of Android Studio -- here are short instructions on how to do that.

To start working with Kotlin on a version that's lower than 3.0 you should install the plugin designed for this purpose. So, launch your Android Studio, then press the Configure menu and choose the Plugins section.

Android Studio with Kotlin: Install plugin

Configure -- Plugins 

After that, install a plugin from JetBrains in the window that appears:

Android Studion with Kotlin: Install JetBrains plugin

Install JetBrains plugin 

After that:

Android Studio with Kotlin: Install Kotlin language

Search -- Kotlin 

Here you go! Restart your Android Studio and you may start working with Kotlin. In case you don't know how to start a project on Kotlin through your Android Studio -- use this official tutorial that will guide you.

As you can see, there are dozens of useful features in Kotlin language that makes developers around the globe want to learn this language and use it for their projects. So, the future of Kotlin is pretty clear.

Some of the developers that are mastering Kotlin even state they'll never come back to Java. Why? Learn in our next article. Subscribe in order not to miss it!

By the way, if you're looking for cooperation -- we are always at your service. Contact our managers to ask your questions and get a free consultation.

Rate this article!

An image An image
Bad!
An image An image
Strange!
An image An image
Boring!
An image An image
Good!
An image An image
Love it!
(1008 ratings, average: 4.8 out of 5)
Latest articles
Back to top
As s part of our team, be ready for:
An image
Competitive Base Salary
An image
Comprehensive Benefits
An image
Great Work Environment
An image
Drug Free Workplace
Tell us more about yourself