Why Kotlin ? — Its advantages

Satyajit Nath Bhowmik
5 min readSep 22, 2017

Why kotlin ?

While there’s been a lot of buzz around Kotlin and google announced that kotlin is first class language for writing android apps — so why should actually use it ?

Kotlin : It’s a Statically typed programming language targeting JVM, Android, JavaScript & Native / Sponsored and Developed by JetBrains. Kotlin compiles to bytecode, so it can perform just as well as Java.

What does Kotlin do that Java doesn’t? — kotlin does most of the things what java does but it does in a better way.

So, As a developer We love clean, concise code. Less code takes less time to write, less time to read, and is less susceptible to bugs — makes our reviewers life better 🙂. let me give one example before I am going to details about kotlin features.

In every project we have number of classes which exist solely to store data or state — may be it contains : -

  1. constructor
  2. Fields to store data
  3. Getter and setter functions
  4. hascode() , equals(), tostring() functions etc.

So how the above things we implement in Java :

Lets take an example to store some user details: —

public class Details {private String firstName;private String lastName;private int age;public Details(String firstName, String lastName, int age) {this.firstName = firstName;this.lastName = lastName;this.age = age;}public String getName() {return firstName;}public void setName(String name) {this.firstName = firstName;}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;}public int getAge() {return age;}public void setAge(int reviewScore) {this.age = age;}@Overridepublic boolean equals(Object details) {if (this == details) return true;if (details == null || getClass() != details.getClass()) return false;Details detailsObject = (Details) details;if (age != detailsObject.age)return false;if (firstName != null ? !firstName.equals(detailsObject.firstName) :detailsObject.firstName != null) {return false;}return lastName != null ?lastName.equals(detailsObject.lastName) :detailsObject.lastName == null;}@Overridepublic int hashCode() {int result = firstName != null ? firstName.hashCode() : 0;result = 31 * result + (lastName != null ?lastName.hashCode() : 0);result = 31 * result + age;return result;}@Overridepublic String toString() {return "Details{" +"firtName='" + firstName + '\'' +", lastName='" + lastName + '\'' +", age=" + age +'}';}public static void main(String []args) {Details s = new Details("Cold", "Play", 21);System.out.println(""+s.toString());}}

So, its almost 40–50 lines of code to store 3 fields of data in java.

Fortunately,

The above code is no longer necessary due to data class concept in Kotlin.

To do the same in kotlin its just one line of code :

- data class Details(val firstName: String, val lastName: String, var age: Int)

Better huh ? — when we specify the data keyword in our class definition Kotlin automatically generates field accessors, hashCode(), equals(), toString() etc.

We can create instance and we can access the members

Example :

 val object: Details = Details (“Cold”, “Play”, 21) println(object. firstName) // Cold
println(object. lastName) // Play
println(object.age) // 21

So, Kotlin requires atleast 20% less code compare to java.

Now, Let me talk about some features which I love about kotlin :

Features :

1) Null Safety :

No more NullPointerExceptions(NPE)

- Types are non-null by default, and can be made nullable by adding a ?

var a: String = “abc”
a = null // compile error
var mightBeNull: String? = null — this variable can be null

2) Java Interoperability :

Kotlin is 100% interoperable with Java. All Java frameworks are available.Existing java code can be called from kotlin.

3) Smart Casts :

The Kotlin compiler tracks your logic and auto-casts types if possible, which means no more instanceof checks followed by explicit casts:

if (obj is String) {
println(obj.toUpperCase()) // obj is now known to be a String
}

4) Adopting Kotlin is very easy :

  • Kotlin classes export a Java API that looks identical to that of regular Java code. So, adopting kotlin is much easier.

5) Operator Overloading :

A predefined set of operators can be overloaded to improve readability.As an example, here’s how you can overload the unary minus operator:

data class Point(val x: Int, val y: Int)  
operator fun Point.unaryMinus() = Point(-x, -y)
val point = Point(10, 20)
println(-point) // prints "(-10, -20)"

6) Extenstion function Kotlin :

Kotlin provides the ability to extend a class with new functionality without having to inherit from the class or use any type of design pattern such as Decorator. This is done via special declarations called extensions.

7) Lambda functions :

Love the lambda function in kotlin 🙂.

Consider the following example that demonstrates the syntax of a lambda expression:

{x, y -> x+y}

This is a simple lambda expression that takes two parameters, x and y, and returns their sum. The parameters of the function are listed before the -> operator and the body of the function starts after the -> operator. This lambda expression can be assigned to a variable and used as follows:

val sumFunction: (Int, Int) -> Int = {x,y -> x+y}

val sum = sumFunction(3,4)

Note that the type of the variable that holds the lambda expression specifies the types of its parameters and its return value.

Creating a higher order function that can accept the above lambda expression as a parameter is just as easy. For example, to create a function that doubles the result of the lambda expression, you would write:

fun doubleTheResult(x:Int, y:Int, f:(Int, Int)->Int): Int {
return f(x,y) * 2
}

You can call this function as follows:

val result = doubleTheResult(3, 4, sumFunction)

There are so many features which kotlin provides and makes writing code easier, better –

Below is the link where it describes the comparison between java vs kotlin

1) https://kotlinlang.org/docs/reference/comparison-to-java.html

We can say :

Kotlin = (Java + extra update new feature for development)

Nothing in life is perfect so neither is kotlin . So below are the some issues people face while using kotlin :

1) The data class feature is very useful to auto generate java bean boilerplate but it imposes some limitations — such classes cannot inherit from anything, nor be inherited from. This in turn makes the “sealed class” feature rather less useful, as you can’t have a sealed hierarchy of data classes.

2) By default, classes are final. You have to mark them as “open” if you want the standard Java behavior.

3) No static analyzers for Kotlin yet.

I will end this blog with writing ‘Hello World’ function as this is the first program may be we try whenever we go for new language:

fun main(args: Array<String>) {
println("Hello World!")
}

And to know more about kotlin : -

Kotlin Reference:

--

--