Getting started with Android and Kotlin

With Google IO 2017, Google announced Kotlin as the officially supported language for Android.

Kotlin will be now shipped with Android Studio working out of the box, starting with version 3.0. No extra installations needed. No more incompatible plugins. All thanks to close collaboration between JetBrains and Google.

Why Kotlin?

Most importantly, it was because we think Kotlin is a great language that will make writing Android apps easier and more enjoyable.

Kotlin is also a great match for the existing Android ecosystem. It is 100% compatible with the Java programming language. We can add as little or as much Kotlin into our existing codebase as we want and mix the two languages freely within the same project.

A Quick Tour

here is a quick tour of some of the particularly appealing aspects of Kotlin:

1.Null Safety

One of the Kotlin’s best features is null safety. The Kotlin compiler enforces that variables that can hold null values are explicitly declared – thus no more NullPointerExceptions at runtime!

var neverNull: String = "something"
var mightBeNull: String? = null // "?" indicates this can be null
if (neverNull.length > 0) {  // This is OK…
   …
}
if (mightBeNull.length > 0) { // Compiler catches this error for us
   …
}

2. Extension Functions

Extension functions are functions that, as the name implies, help us to extend the functionality of classes without having to touch their code.

In other words, the extension functions in Kotlin allow us to extend the functionality of a class by adding new functions. The class doesn’t have to belongs to us (could it be a third party library) and also without requiring us to inherit the class.

Really? without inheriting the class.

Yes! It’s possible in Kotlin.

Let’s stop talking, will show how it is possible.

Taking a very simple example to understand. Suppose we need to load the image using the Picasso library:

//Using Java
Picasso.with(imageView.context).load(url).into(imageView)
//Creating extension function with Kotlin
fun ImageView.loadUrl(url: String) {
    Picasso.with(context).load(url).into(this)
}

//calling extension function
imageView.loadUrl(url)

3. Default Argument

Function parameters can have default values, which are used when a corresponding argument is omitted. This allows for a reduced number of overloads compared to other languages.

4. Named Argument

Function parameters can be named when calling functions. This is very convenient when a function has a high number of parameters or default ones.

fun reformat(str: String,
            normalizeCase: Boolean = true,
            upperCaseFirstLetter: Boolean = true,
            divideByCamelHumps: Boolean = false,
            wordSeparator: Char = ' ') {

            ...
}

we could call this using default arguments

reformat("kotlin")

5. Kotlin is concise

One of the main advantages of Kotlin is its concision. We get more functionality with less code. And the less code we write, the fewer mistakes we make. It’s pretty straightforward.

//Data model class written in java
public class Person {

private String id;
private String name;

public Person(String id, String name) {
this.id = id;
this.name = name;
}

public String getId() {return id;}

public void setId(String id) {
this.id = id;
}

public String getName() {return name;}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "Person{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}

@Override
public boolean equals(Object o) {
return super.equals(o);
}

@Override
public int hashCode() {
return super.hashCode();
}
}
//An equivalent class written in Kotlin.
data class Person(var id: String,var name: String)

Yes, we’ll automatically get needed getters, setters, equals(), hashcode(), toString() and copy() functions for our data class! Of course, we can easily override these functions, but in most cases it’s enough just to declare the class and its properties.

6. Remember filtering lists with for loops?

Thanks to the functional approach to collections, we can also reduce all the complex, multiline instructions to only one line of code.

//How collections were handled in Java
void processList(List<Integer> list) {
  List<> stringList = new ArrayList<>();
    for (Integer i : list) {
      if (i % 2 == 0) {
        stringList.add(i.toString());
      }
    }
}
//How Kotlin handles collections
fun processList(list: List<>) {
  val stringList = list.filter { it % 2 == 0 }. map { it.toString() }
}

7. No More findViewById

We all Android Developers have been bored writing findViewById to bind the views. Kotlin Team realized it and they gave us Android Extensions.

Kotlin Android Extensions are another Kotlin plugin that is included in the regular one. It eliminates the need of findViewById in our code.

Go to your gradle module file and add

apply plugin: 'kotlin-android-extensions'

That’s it! The setup is done! We can directly get the view in our Activity by the id specified in the layout.

Under the hood: Internally the compiler creates a small hidden cache function which callsfindViewById for every view on that Activity or Fragment giving us the synthetic property to use the view.

8. Control Flow

If Expression: In Kotlin, if is an expression, i.e. it returns a value. Therefore there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.

// Traditional usage
var max = a
if(a < b) max = b
// With else
var max Int
if(a > b) {
   max = a
} else {
   max = b
}   

// As expression
val = if(a > b) a else b

When Expression: when replaces the switch operator of C-like languages. In the simplest form it looks like this.

when(x) {
     1 -> print("x == 1")
     2 -> print("x == 2")
     else -> { // Note the block
         print("x is neither 1 nor 2")
     }
}

when matches its argument against all branches sequentially until some branch condition is satisfied. when can be used either as an expression or as a statement. If it is used as an expression, the value of the satisfied branch becomes the value of the overall expression.

Some of my favorite Kotlin features:

  1. Replacing simple if/else if/else blocks with when
  2. Extension function
  3. No more view binding
  4. Functions in one line
  5. Beautifying even the ugliest click handlers
  6. Reducing the need for`if (whatever != null)`

Getting Started

If you want to get started with Kotlin, you can start playing with code online immediately here. Just hit the green triangle to compile and run.

Happy Coding 🙂

Advertisements

One thought on “Getting started with Android and Kotlin

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s