Sitemap
Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Why Kotlin over Java

--

The article delivers some notable features of Kotlin over Java.

Before jumping into the Kotlin its essential to know the importance of Java.

Java:

Java is the most popular and widely used object oriented programming language. Java is mainly used to develop Enterprise applications, Android application and Server-side programming.

Kotlin:

Kotlin is also a object oriented programming language which is interoperable with Java. For example, a Android application can be half coded in Java and the other half in Kotlin. Lets understand how?

Kotlin is a JVM based language just like Java, i.e. The the Kotlin compiler after compilation generates the byte code which is same as that of Java’s byte code produced by Java compiler. Thus both can run on JVM.

Press enter or click to view image in full size

Is Kotlin faster than Java? Kotlin’s performance is comparable to Java’s performance. Thus Kotlin offers same runtime as Java.

Note: Java has improved over the years but the one I have used here might be outdated.

What makes Kotlin better?

Syntax is one of the Kotlin’s biggest advantage. Kotlin requires significantly lesser code than java, which makes code look more simpler and readable.

Lets try to understand it better,

1.Null-Safety

Heard about billion dollar mistake? its the NULL reference.

Lets take a practical example, Suppose you are doing a API call and expecting a String response from the server. But somethings goes wrong underway. What do you get as response? its null!


String respose = <Response from API>;

System.out.println(response.length());// You are actually trying to do null.length()

What do you expect here,

Exception in thread "main" java.lang.NullPointerException
at Temp.main(Temp.java:7)

Java Solution:

String response = <Response from API>;

if(response != null)
{
System.out.println(response.length());
}
else
{
System.out.println((String)null);
}

The above solution looks pretty obvious but lengthy too.

Kotlin comes with a null safety operator (?)

Kotlin distinguishes variables in Nullable and Non-Nullable


Kotlin Non-nullable:

var name:String = "Kotlin"
name = null // compilation error


Kotlin nullable:

var name : String? = "Kotlin"
name=null //no compilation error


Java:

String name = "Java";
name = null // No compilation error

Kotlin Solution:

var response: String? = <response from api>

println(response?.length);

response?.length returns the length of the string if response is non-null else it returns null. Thus its a replacement for Java’s if-else check.

2. Data classes:

Object oriented programming mainly deals with real world objects. Thus entities are always the part of our project. Most of the time we require a class with only members variables (States only) to store data. Example: Student, Course

Entity: Student
Attribute: Name, USN, DOB, Email id, Address, Phone number and more.

Java Solution:

public class Student {

private String name;
private String USN;
private String emailID;
private String address;

public Student(String name, String USN, String emailID, String address) {
this.name = name;
this.USN = USN;
this.emailID = emailID;
this.address = address;
}

public String getName() {
return name;
}

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

public String getUSN() {
return USN;
}

public void setUSN(String USN) {
this.USN = USN;
}

public String getEmailID() {
return emailID;
}

public void setEmailID(String emailID) {
this.emailID = emailID;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

}

Now lets print the object of Student class,


class Main
{

public static void main(String[] args)
{
Student student = new Student("Sandeep","2342","hi@example.com","Bengaluru");
System.out.println(student);
}

}
Output: 

Student@3fee733d

This doesn’t seem to the expected output, hence the solution for this is overriding toString() in the Student class.

@Override
public String toString() {
return "Studentt{" +
"name='" + name + '\'' +
", USN='" + USN + '\'' +
", emailID='" + emailID + '\'' +
", address='" + address + '\'' +
'}';
}

Now it works fine. But that is a lot of code.

Kotlin Solution:

Kotlin comes with a data class which doesnt require getters and setter, toString().

data class Student(var name:String,var USN:String, var emailId:String,var address:String)

Done! now lets populate some data and print it:

fun main()
{
var student: Student = Student("Sandeep","2342","mssk@example.com","Bengaluru")
println(student);
}
Output:

Student(name=Sandeep, USN=2342, emailId=mssk@example.com, address=Bengaluru)

3.String templates:

Get Sandeep Kamath’s stories in your inbox

Join Medium for free to get updates from this writer.

Print functions are widely used in every programming language. How do we print a variable along with string description to it?

Java Solution:

class Main
{

public static void main(String[] args)
{
String name = "XYZ";
System.out.println("My name is " + name + ", I am ......(your story)");
System.out.println("Length of the string is " + name.length());
}

}

Kotlin solution:

${variable_name}

fun main()
{
var name = "XYZ" //need not need to define datatype in kotlin
println("My name is $name I am ......(your story)")
println("Length of the string is ${name.length} ")
}

4. Extension Functions:

Kotlin extension function provides a facility to “add” methods to class without inheriting a class or using any type of design pattern.

Say you have a Kotlin Inbuilt Class with some method defined in it and you want to add more functions. This is achived using extension functions.

Example: MutableList<> is the List in Kotlin and you want to add swap function to it.

fun MutableList<Int>.swap(index1: Int, index2: Int):MutableList<Int> 
{
val tmp = this[index1] // 'this' represents to the list
this[index1] = this[index2]
this[index2] = tmp
return this
}

fun main(args: Array<String>) {

val list = mutableListOf(5,10,15)
println("before swapping the list :$list")
val result = list.swap(0, 2)
println("after swapping the list :$result")

}

5. Singletons:

Singleton classes are classes with only one instance/object. This is widely used in android to achieve a single instance of API request queue (Volley library).

Java Solution:class Singleton
{
private static Singleton singleton=null;

// have constructor, variables, methods here.

public String name = "XYZ";

public static synchronized Singleton getInstance()
{

if(singleton==null)
singleton = new Singleton();

return singleton;

}

}

Class Main
{
public static void main(String[] args)
{

Singleton s1 = Singleton.getInstance();
Singleton s2= Singleton.getInstance();
// Here s2 is equivalent (pointing) to s1 and thus only one object can be created.
}
}

The above implementation is self explanatory i.e. getInstance() return a new object only for the first time.

Kotlin Solution:

Object Singleton
{
var name:String = "XYZ";
// have init, variables, methods here.
}

fun main()
{
println("${Singleton.name}");
}

6. Smart Casts:

In most cases, you don’t need to use explicit cast operators in Kotlin because the compiler tracks the is-checks and explicit casts for immutable values and inserts (safe) casts automatically when necessary:

fun demo(x: Any) {

if (x is String)
{

print(x.length) // x is automatically cast to String

}

//When is switch statement in Kotlin

when (x) {

is Int -> print(x + 1)

is String -> print(x.length + 1)

is IntArray -> print(x.sum())

}

}

7. Many More:

There are many other functionalities provided by Kotlin which makes it better than Java.

Some of them are:

Bonus:

Kotlin is not only better that Java in syntax but also provides powerful yet lightweight Framework.

Ktor for RESTful API:

Kotlin’s Ktor vs Java Spring boot:

Both are equally good, but Kotlin’s Ktor is comparatively lighter and simpler in setup/integration compared to spring boot. Kotlin’s coroutines also is a plus point.

Here’s the simple Authorization RESTAPI using Ktor,

My sincere apologies for any errors in the article, Thanks for your time, I hope it was helpful.

--

--

Sandeep Kamath
Sandeep Kamath

Written by Sandeep Kamath

Software Engineer who loves turning ideas and words into stories.