Why use Kotlin ?

In this blogpost, I am going to take a dive into some of the most widely used features of Kotlin and see if they are attractive enough for us to make the switch. First let us start with some background/ history. Kotlin was started sometime back by the same guys (Jetbtrains inc.) who created the wonderful Java IDE and had this same motivation to create a completely new JVM based language. The biggest advantage of using Kotlin is that it helps in writing much more concise ,clean and also safe code.

Let us browse through some of the key features of the Kotling language (please also refer to my Github project KotlinExperiments:

  var firstName = "Soumik"
  var lastName = "Mukherjee"
  const val age = 40
    var name : String = "Soumik"
    //below line generates a compile time error
    //name = null

    var surname: String? = "Mukherjee"
    // below line does NOT generate a compile type error as we have used a nullable type
    surname= null
    
    // Also the ?. operator ensures that the name will not be invoked in case empObject is null
     println(empObject?.name)
  fun calculateSalaryBasedOnAgeAndDepartment(department: String, age: Int = 40) : Double

So in the above function declarataion, the caller can optionally specify the second parameter (age) and in case the caller does not specify that parameter - it will take the default value 40.

  calculateSalaryBasedOnAgeAndDepartment(age=30, department = "IT");

The above two aspects (default parameters in function declaration and ability to call a function with named parameter)- have made method overloading and builder methods completely redundant and in my opinion - this is one of the smartest enhancements in Kotlin.

  // class instantiated with zero argument constructor
  var studentObject= Student()
  
  // class instantiated with one argument constructor
  var empObject = Employee ("Soumik") 

Also the data class concept (which represents/symbolises value objects) reduces boilerplate code to a great extent. Please refer to the below example:

  data class Employee (val name: String, val age: Int, val designation: String, val Salary: Long) 

The above line of the code is equivalent to some 20 lines of Java code with all getters and setter methods and also with equals() and hashcode() methods. However with usage of Lombok with java - the boilerplate in java code can also be reduced.