Direkt zum Inhalt

Kotlin Language for Android

Kotlin Language for Android


Kotlin language is the new addition to the list of programming languages and the new official android language announced in Google io17. This was a big news in android development especially to those who do development natively. Here in Buzzwoo! Asia, as an IT Software company, we also make sure that we take our part in spreading this exciting news. Not just by words, but by work. This is by organizing Kotlin programming training for the developer’s community here in Chiang Mai, Thailand.
 

Many Android developers are still doubting or hesitating to explore this new language. Whatever their reasons are, that we can only assume. If you are one of those who has doubts or one of those who wants to start android development using the language, you are on the right page of your browser. We hope that through this article, we are able to help you understand why Kotlin is the next big thing in the Android development world.

What is Kotlin?

Kotlin was officially announced as an official Android programming language since Google io17. A statically typed programming language developed by JetBrains targeting JVM, Android, Javascript, and Native under the license of Apache 2 as an open source project.

Why should it be Kotlin?

  • First and foremost, Kotlin is not entirely a new language. This is developed on top of Java for the JVM. Thus, for the native java android developers, learning this language will be smooth and easy.

  • Kotlin is a null safe programming language removing NPEs (Null Pointer Exceptions) or also known as the billion dollar mistake at runtime and move it during compile time.

  • A pragmatic language from the industry for the industry. Kotlin is not like any other popular programming languages that came from the academics, instead, Kotlin is created from the industry to solve real problem the developers encounter in the real world scenarios.

  • 100% interoperable with Java.

  • Expressive and concise. Less code == more readable.

What does Android have to say about it?

  • You don’t need to use findViewById and/or type casting to use my components. Use Anko (https://github.com/Kotlin/anko).

  • You don’t need more utils classes in your project. Just extends the utils classes or any classes in my SDK or in your project.

  • Less is more. Do less code and less implementation, faster development and faster deployment.

 

So let’s get started!

What do you need?

Android Studio 3.0, at least. There are other IDEs that you can use for Kotlin development but, we don’t want to you go through the difficulties in setting it up. The Android Studio 3.0 is the easiest and fastest way to get you started. Download and install the tool from the link below and you are set for android development using Kotlin programming.  Here is the link:  https://developer.android.com/studio/index.html

 

Kotlin is a very powerful high-level programming that sits on top of Java programming language. It has powerful SDK that could help developers in performing their jobs faster that requires a small amount of time. In this article, we will only highlight few of Kotlin’s capabilities that make it the future of Android application development


Nullability

This is best represented by ‘?’ (question mark)  and ‘!!’ (double exclamation mark). Adding a suffix of ‘?’ will tell the compiler that the property can be of nullvalue ( ‘?’ == can have a value of null). Here’s an example:
 

var firstname: String = "John Doe"

 

The above is Kotlin’s way of declaring a property. It starts with the var keyword, followed by the property name and the data type which is separated with a colon (:), finally the initial value will follow separated by an equal symbol(=). The above statement also cannot have a value null at all times. If you want to declare a property that later on can be assigned to a value null, you must add the nullability symbol after the data type like this:
 

var firstname: String? = "John Doe"
 

While suffixing with ‘!!’ when getting or setting a value of a property, will inform the compiler that at anytime, the property cannot have a value of null like below:
 

var length = firstname!!.length

 

One should be careful when using this non-nullable symbol. Although Kotlin is null safe, it does not guarantee you that you won’t have crashes of your application at runtime because of NPE. You will still have crashes caused by NPE if you carelessly use the ‘!!’ symbol. So make sure when using the non-nullable symbol, you are sure that the property will not have a null value at all times.
 

when Statement

Using the if-else and switch statements the usual way can still be done and it is not discouraged in Kotlin. However, Kotlin introduces the when statement. This is not to replace the if-else or the switch statement that we have in Java, but an additional option.

Example:

 

var number = 1

when (number) {

  1 -> println("Number is $number")

  2 -> println("Number is $number")

  else -> println("Number $number is unknown.")

}
 

for Loop

Below examples are another extensions of using for loop in Kotlin. The typical way of using for loop will still work perfectly with Kotlin programming.
 

  • The using of in

for (animal in animals){

  println(animal)

}
 

  • The looping by each index

for (index in animals.indices) {

  print(animals[index])

}

 

  • forEach loop

animals.forEach {

  print(it)

}
 

  • forEachIndexed loop

animals.forEachIndexed {

  index, s -> println(s)

}

 

Interoperability

Kotlin is 100% interoperable with Java. Which means, that both Kotlin and Java classes can talk and understand each other and work together as expected. Thus, any class, methods/functions, and variables/properties can be used or called from a Kotlin or from a Java class.  Kotlin and Java classes may also be mixed in one project. Saying all these, all the existing java libraries that you want to include in your project will work perfectly as it should be.


 

Kotlin Functions

1.Basic Function

The function construct in Kotlin is keyword function_name(parameter_name: data_type): return_data_type. The return type of a function can be any data type or it can be a Unit. Unit is like void in Java programming. An Example of our Kotlin getter function will be:

 

fun getFirstName(): String {

  return "John Doe"

}

 

Below is an example of a shorter way to create a getter and setter function of a class property.

var firstname: String

  get() = firstname

  set(value) {firstname = value}

 

2.Function Expression

Kotlin as a concise and expressive language, it has made evolution of function creation in android development, giving birth to what is called function expression.

Given this function:
 

fun getFirstName(): String {

  return "John Doe"

}

 

We can transform this into a function expression like this:
 

fun getFirstName(): String = "John Doe"

A function with a single line of code but works the same as it is expected.
 

3.Function Extensions

One powerful capability in Kotlin programming is that it gives you the power to extend any existing classes in your project including the libraries or even the Kotlin and Android SDK classes. This is less is more with Kotlin. Using Java in android development, in order to initialize an adapter, we have to do this:

ListAdapter adapter = new ListAdapter(listOfData);
 

RecyclerView.LayoutManager layoutManager = new

LinearLayoutManager(this);

recyclerView.setLayoutManager(layoutManager);

recyclerView.setAdapter(adapter);

Imagine if you have many adapters in your application, then you might need to have the same above code everytime. But, with Kotlin function extension, we only need to extend RecyclerView class and add additional behavior to the class. To do that, we first need to extend the RecyclerView class and add a function init (this is just a sample function name), that accepts a parameter of type RecyclerView.Adapter.  Our function extension will then look like this:
 

fun RecyclerView.init(_adapter:

RecyclerView.Adapter<RecyclerView.ViewHolder>) {

  this.layoutManager = LinearLayoutManager(context)

  this.isNestedScrollingEnabled = false

  this.adapter = _adapter

}
 

When we want to initialize our RecyclerView using our newly added behavior to the class, we simply need this single line of code :
 

recyclerView.init(RecyclerViewAdapter())

where :

recyclerView is RecyclerView component in your layout

RecyclerViewAdapter is your adapter that extends the

RecyclerView.Adapter class

 

Kotlin Class

True to its conciseness and expressiveness, Kotlin transforms class creation to a single line of code at the very least. Let us explain it using the code. In Java programming, we create a function like below.

 

public class Person {

  private String firstname;

  private String lastname;


 

  public Person(String firstname, String lastname) {

      this.firstname = firstname;

      this.lastname = lastname;

  }

  // getters and setters

}


However, Kotlin said that it is too long and in fact creating those lines of code not to mention the getters and setters takes so much time and effort. So, Kotlin finally said, you can do it on a single line like below:


class Person(var firstName: String, var lastName: String)


Creating an instance of a class in Kotlin does not need the new keyword. Take note also that in the examples above, the semi-colon (;) is not used because Kotlin makes it optional.

Conclusions

Above are just few things included in Kotlin programming language. We are showing you how powerful Kotlin can be in developing an android application and we hope are able to ignite your curiosity on the language or clear some doubts on Kotlin language and hopefully this article will let you start exploring more about Kotlin or even start using this language in your android application development.

For more information about the Kotlin language and its SDK, you can visit their page here:
https://kotlinlang.org/


 

Über den Autor:
/

Wie können wir Sie unterstützen?

Kontaktieren Sie uns

Copyright © 2017 BUZZWOO! GmbH & Co. KG