Posted in

Enhancing your Development with Kotlin

Right since it was announced in Google IO 17, Kotlin has been a big hit among developers and many are now switching their development from traditional Java to Kotlin. My aim is that after reading this article you start using Kotlin for your daily tasks or wherever you have been using Java. So let’s start!

(Note we might cover some core Java concepts in this article)

With help from a big community of developers, Kotlin was developed by JetBrains, which is a software tooling company, as an open source project. So if someone asks you, what is Kotlin, you’d say just like Java it is a statically typed language for computational purposes while supporting both functional programming and object-oriented programming paradigms.
Being said that it’s statically typed, you can omit types in Kotlin, making it look concise as some dynamically-typed languages.

Talking not Kotlin and not talking about interoperability won’t be fair. Kotlin is cent percent interoperable with Java, and we will see that later. You must know that Kotlin is not only for JVM or Android development, you can also compile Kotlin code to JavaScript or even to native code. So you can also do server side and frontend development in Kotlin. Community plays an important role in developing this pragmatic language and you can check this initiative called KEEP (Kotlin Evolution and Enhancement Process).

Kotlin and Java

If you are a Java developer then it is really easy to start with Kotlin. Kotlin supports all existing Java libraries and frameworks. Also, since it’s 100% interoperable you can even mix Kotlin and Java code in one project.

Kotlin code is directly compiled to the Java bytecode, and you can use some tools that automatically convert your Java code to Kotlin code, and this comes handy when you are adding Kotlin to your existing Java project. Let’s now see some Kotlin code in action.

So, we have a simple data class in Java which looks like this –

public class News {

   private String title;

   public News(String title) {
       this.title = title;
   }

   public String getTitle() {
       return title;
   }

   public void setTitle(String title) {
       this.title = title;
   }
}

In Kotlin this becomes –

        class News(val title: String)

Much more simple and concise ;]

Under the hood, the class looks the same and behave the same at the bytecode level similar to it’s Java analogue. Moreover, if you add the data modifier to this class it will generate some additional useful methods like equals, toString, and hashCode. Let’s now create an object of this class –

In Java –

    News news = new News("Kotlin Example");
    System.out.println(news.getTitle());

In Kotlin –

    val news = News("Kotlin Example");
    println(news.title);

Note that we don’t need a new keyword in Kotlin and you call the constructor just like a regular function.

Let’s look at another example –

public void funAge(int age){
   String description;
   Color color;
   if (age < 18){
       description = "teenager";
       color = BLUE;
   }
   else if(age > 18){
       description = "adolescent";
       color = ORANGE;
   }
   else {
       description = "old";
       color = RED;
   }
}

A simple method that takes age as an argument and update values of description and color. If you use automatic code converter it will look like this In Kotlin –

fun funAge(age: Int){
   val description: String
   val color: Color
   if (age < 18){
       description = "teenager"
       color = BLUE
   }
   else if(age > 18){
       description = "adolescent"
       color = ORANGE
   }
   else {
       description = "old"
       color = RED
   }
}

But we can improve it using the power of Kotlin! You can see the description variable is repeated several times and we can avoid it by using the Pair class that represents a generic pair of two values –

fun funAge(age: Int){
   val (description: String, color: Color)=
   if (age < 18){
       Pair("teenager",BLUE)
   }
   else if(age > 18){
       Pair("adolescent",ORANGE)
   }
   else {
       Pair("old",RED)
   }
}

So we initialize two variables at once. As discussed above we can also omit types when the context is clear so you can write this as

fun funAge(age: Int){
   val (description, color)=
    // ¦ ¦ ¦..
}

The compiler will infer the types for us.

Also in Kotlin, there is something called as when expression, which is kind of analogous to switch, allowing you to enumerate several options. There is also a to, which converts a tuple of type Pair(from docs). So now our code becomes –

fun funAge(age: Int){
   val (description,color)= when{
       age < 18 -> "teenager" to BLUE
       age > 18 -> "adolescent" to ORANGE
       else -> "old" to RED
   }
}

So the Java to Kotlin converter might not always produce the idiomatic Kotlin code and you’ll have to manually improve it. In Kotlin we also have `in` and it is used for iteration and for checking the `belonging`, that is, if certain key belongs to a range or not.

Let’s now look at a simple HelloWorld Kotlin program –

fun main(args: Array<String>){
   val name = if (args.size > 0) args[0] else "World"
   println("Hello, $name!")
}

The program outputs Hello, World! If no arguments are passed. In Kotlin, you no longer need to put everything inside a class! Also, note that in Kotlin, `if` is an expression. So you can assign that to a variable or return it from a function. Kotlin also provides you with String templates, in which you can pass the value of a variable or also pass complex expression like a function call. Kotlin has two main keywords to define variables,

  • val – this is a `read-only` variable and you can think of it as a final variable in Java as it can’t be reassigned.
  • var – this is a mutable variable which you can reassign.

Another advantage of Kotlin is that you can define functions in every scope, so

  • At the top level –

fun topLevel() = 1

  • Member function at the class level –

class Example {
    fun member() = 2
}

  • Local function at the class level –

fun member() {
    fun local() = 3

Let’s now look a sample code and see what it prints –

println(listOf('a', 'b', 'c').joinToString(
    separator = "", prefix = "(", postfix = ")"))

As you might have guessed we join the contents of the list and it outputs –

(abc)

In this code snippet, we have used the concept of named arguments. So we can specify the name of arguments directly in the code. In Java, you need to explicitly type the overloaded versions of a method, but in Kotlin you can use this feature directly.

Now let’s talk a bit about Exceptions. Kotlin doesn’t differentiate between checked and unchecked exceptions, and handling an exception is a personal choice. Also, it is not mandatory for your function to specify the exception it can throw!  So, no more Null Pointers now ;]

Also throw, is an expression in Kotlin, and you can assign the result of `throw` to a variable.

Similarly try is also an expression, and you can again assign the result to a variable.

There are some things in Kotlin which are not analogous to Java. Extension functions extend the class. It is defined outside of the class but can be called as a regular member of the class. Though extension function in by default visible in the whole project and you need to import it explicitly.

On the root, Kotlin Standard Library is just Java Standard Library plus extensions, and that provides very smooth interoperability between Java and Kotlin. So I highly recommend using Kotlin to develop apps.

Kotlin also provides support to lamdas. Lambdas is an anonymous function that can be used as an expression and can be passed as an argument to another function invocation.

With Android Studio 3.0 you can now choose to support Kotlin and you can get started with Kotlin samples in the Google Codelabs. Kotlin is not a purely functional language and with OOP design you are also using the function paradigms of this language. There is a nice section that describes as to why Kotlin was officially supported in Android. Check it here.

Mobile apps developer and technical writer at Nex Mobility for more than 7 years. I have a professional development team for Xamarin, Android and iOS apps. We are also providing best outsourcing services and give end to end solution of aaps programming.

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.