#TECH

Why is Kotlin one of the most loved programming languages?

Over the last year and a half, I was working primarily on Kotlin codebase. I was lucky enough to get the chance to start the project from scratch and there were many reasons why I chose Kotlin for my project.

Really, many? 

No, I’m kidding! Initially. there was just one reason- Kotlin was announced as Android’s official language and I wanted to try it out myself.

As time passed and I  explored the language, I started getting curious about this language and  got hooked to other reasons.

In this blog, I will cover my personal experiences on working on Kotlin codebase. I’ll discuss some of the most lovable features of Kotlin which make it an interesting programming language.

kotlin

The transition from Java to Kotlin

Initially, I had imagined that learning kotlin would be a tough job.I started learning Kotlin by creating some simple programs instead of directly using them in Android.

Surprisingly, I got comfortable in Kotlin quickly because  Kotlin is also a JVM based language so things are quite relatable. In my opinion, if you are a beginner, you too should start with Kotlin basics and create some simple programs so that you become aware of Kotlin syntax. Don’t go with android studio’s code converter in initial phase of your learning otherwise things will become challenging in future.

Once you read out the basics of Kotlin and feel comfortable enough to write code then you can start with your existing Android Project to convert it into Kotlin. Parallely, you can also explore the kotlin feature, understand them and implement them gradually.This was the approach I followed to make a transition from Java to Kotlin.

Features I love:-

Null Safety

One of the most common pitfalls in many programming languages, including Java, is that accessing a member of a null reference will result in a NullPointerException.

Kotlin aims at being a safer language.In Kotlin, by default variables are non-null references and cannot be set to null. You can make variables nullable by adding “?” to the end of the variable. Once you do this, the compiler tries to make sure you use the variable safely for the duration of its lifecycle by using compile-time checks.

a) Safe Calls (?.)

This calls the method if the property is not null or returns null if that property is null without throwing an NPE (null pointer exception).

nullableVariable?.someMethodCall()

b) The !! Operator

This (!!) operator is used to explicitly tell the compiler that the property is not null and if it’s null, please throw a null pointer exception (NPE)

nullableVariable!!.someMethodCall()

This is my favourite feature of Kotlin. It’s extremely helpful when you want to build crash-free apps. NullPointerException is a million dollar problem that every developer faces.You can easily say goodbye to NullPointerException by using this feature.

Null safety force us to cater to all the scenarios that result in crash free apps.

Scope Functions

Let’s talk about scope functions

Kotlin “scope functions” are functions that allow for changing the scope, or the range of a variable. Such functions are included in the Kotlin standard library: “apply”, “run”, “with”, “let”, and “also”.

a) apply – I personally use “apply” the most. So I would like to start with this…

The first option is for the value to be the object itself. Kind of like a builder. This is how “apply” works.

fun showDialog() {
  val builder = AlertDialog.Builder(this).apply {
      title = "Test Scope Functions"
      setPositiveButton("Cancel") { _, _ -> Log.i("Positive Click", "Clicked")
      }}
  builder.create().show()
}

 

b) run — returns anything you want and re-scopes the variable it’s used on to this

val password: Password = PasswordGenerator().run {
  seed = "someString"
  hash = {s -> someHash(s)}
  hashRepetitions = 1000
  generate()
}

 

c) let — mostly used to avoid null checks, but can also be used as a replacement for “run”. The difference is, that this will still be the same as before and you access the re-scoped variable using “it”

val fruitBasket = ...
apple?.let {
  println("adding a ${it.color} apple!")
  fruitBasket.add(it)
}

 

d) also – use it when you want to use “apply”, but don’t want to shadow “this”

class FruitBasket {
  private var weight = 0

  fun addFrom(appleTree: AppleTree) {
      val apple = appleTree.pick().also { apple ->
          this.weight += apple.weight
          add(apple)
      }
      ...
  }
  ...
  fun add(fruit: Fruit) = ...
}

Extension Functions

What if you want to add some functionalities in third party libraries whose code you can’t edit? In such cases, extension functions are a blessing.

Extending a class with functionality without needing to edit the original class. Good for libraries whose code you can’t edit.

 fun Context.showToast(text: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
      Toast.makeText(this, text, duration).show()
  }

//to call this method from any context extending class

showToast(“Hello”)

Data Classes 

We often need to create classes whose primary purpose is to hold data. In Java, these classes generally contain the same old boilerplate code in the form of getters, setters, equals(), hashcode() and toString() methods.

Consider the following example of a Customer class that holds only the Customer data –

public class Customer {
    private String id;
    private String name;

    public Customer(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 boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Customer customer = (Customer) o;

        if (id != null ? !id.equals(customer.id) : customer.id != null) return false;
        return name != null ? name.equals(customer.name) : customer.name == null;
    }

    @Override
    public int hashCode() {
        int result = id != null ? id.hashCode() : 0;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }
}

 

Isn’t it too long and messy? What if all this can be done in one line?

Is it possible? Yes, Kotlin can do this for you…

You can create Kotlin data classes like this

data class Customer(val id: Long, val name: String)

Kotlin data classes automatically create getter/setter and implement equals(), toString() methods.


After completing my first project in Kotlin, I realized why it is being loved so much, especially among the Android developers. Now, if someone asks me why they should consider choosing Kotlin over Java for Android Application Development, I’m sure I can convince them with a handful of reasons.

I think you would also fall in love with Kotlin after reading these features. Have I convinced you yet?

 

You might also like