Overview of Kotlin and Comparison Between Kotlin and Java

What is Kotlin?

Kotlin is a new programming language from JetBrains. It first appeared in 2011 when JetBrains unveiled their project named “Kotlin”. Kotlin is an Open-Source Language.

Basically like Java, C and C++ - Kotlin is also “statically typed programming language”. Statically typed programming languages are those languages in which variables need not be defined before they are used. This means that static typing has to do with the explicit declaration or initialization of variables before they are employed.

As Earlier said that Java is an example of a statically typed language, similarly C and C++ are also statically typed languages.

Basically, Static typing does not mean that we have to declare all the variables first before we use them. Variables may be initialized anywhere in the program and we (developers) have to do so, to use those variables anywhere in the program when there is a need. Consider the following example -


/* Java Code */
static int num1, num2; //explicit declaration
num1 = 20; //use the variables anywhere
num2 = 30;


/* Kotlin Code*/
val a: Int
val b: Int
a = 5
b = 10

In addition to the classes and methods of object-oriented programming, Kotlin also supports procedural programming with the use of functions.

Like in Java, C and C++, the entry point to a Kotlin program is a function named “main”. Basically, it passed an array containing any command line arguments. Consider the following example -


/* Kotlin Code*/
/* Simple Hello Word Example*/

//optional package header
package hello

//package level function, which return Unit and takes an array of string as parameter
fun main(args: Array < String > ) {
 val scope = “world”
 println(“Hello, $scope!”) //semicolons are optional, have you noticed that? :)
}

Filename extensions of the Java are .java, .class, .jar but on the other hand filename extensions of the Kotlin are .kt and .kts.

Benefits of Kotlin Language


val name: String = null // tries to assign null, won’t 	compile.

fun getName(): String = null // tries to return null, won’t 	compile.

Features of Kotlin Language

But in some special cases if we need nullability in our program then we have to ask Kotlin very nicely. Every Nullable type require some special care and treatment. We can’t treat them the same way         as non-nullable types and this is a very good thing.

We have to add “?” after the variable type. Consider the following example - Kotlin also fails at compile-time whenever a NullPointerException may be thrown at run-time. Consider the following example -


val name: String ? = null //assigned 	null and it will compile 	also.

fun getName(): String ? = null //returned null and it 	will compile too.


/* won’t compile */
val name: String ? = null
val len = name.length

/* correct way */
val name: String ? = null
val len = name ? .length

 

 

Consider the following example -



/* 	Java program */

public class Address {

 private String street;

 private int streetNumber;

 private String postCode;

 private String city;

 private Country country;

 public Address(String street, int streetNumber, String postCode, String city, Country country) {

  this.street = street;

  this.streetNumber = streetNumber;

  this.postCode = postCode;

  this.city = city;

  this.country = country;

 }

 @Override
 public boolean equals(Object o) {
  if (this == o) return true;

  if (o == null || getClass() != o.getClass()) return false;

  Address address = (Address) o;

  if (streetNumber != address.streetNumber) return false;

  if (!street.equals(address.street)) return false;

  if (!postCode.equals(address.postCode)) return false;

  if (!city.equals(address.city)) return false;

  return country == address.country;
 }

 @Override
 public int hashCode() {
  int result = street.hashCode();

  result = 31 * result + streetNumber;

  result = 31 * result + postCode.hashCode();

  result = 31 * result + city.hashCode();

  result = 31 * result + (country != null ? country.hashCode() : 0);

  return result;

 }

 @Override

 public String toString() {

  return "Address{" +

   "street='" + street + '\'' +

   ",     streetNumber=" + streetNumber +

   ",     postCode='" + postCode + '\'' +

   ",     city='" + city + '\'' +

   ",     country=" + country +

   '}';

 }

 public String getStreet() {

  return street;

 }

 public void setStreet(String street) {

  this.street = street;

 }

 public int getStreetNumber() {

  return streetNumber;

 }

 public void setStreetNumber(int streetNumber) {

  this.streetNumber = streetNumber;

 }

 public String getPostCode() {

  return postCode;

 }

 public void setPostCode(String postCode) {

  this.postCode = postCode;

 }

 public String getCity() {

  return city;

 }

 public void setCity(String city) {

  this.city = city;

 }

 public Country getCountry() {

  return country;

 }

 public void setCountry(Country country) {

  this.country = country;

 }

}


/* 	Kotlin Program */

data class Address(var street: String,

 var streetNumber: Int,

  var postCode: String,

   var city: String,

    var country: Country)

You May Also Love To Read Deploying Kotlin Application on Docker & Kubernetes

Compilation Speed Java vs Kotlin

We were actually very much interested in knowing the compilation speed of Kotlin as compared to Java.

Difference Between Kotlin And Java


/* 	Java Code 	*/

class Book {

 private String title;

 private Author author;

 public String getTitle() {

  return title;

 }

 public void setTitle(String title) {

  this.title = title;

 }

 public Author getAuthor() {

  return author;

 }

 public void setAuthor(Author author) {

  this.author = author;

 }

}

But in Kotlin the above same class can define concisely in one line -


/* 	kotlin Code */

data class Book(var title: String,
 var author: Author)

It will also allow us to easily make copies of data classes with the help of copy()-


val book = Book(“Kotlin”, “JetBrains”)

val copy = book.copy()

 


fun MutableList < Int > .swap(index1: Int, index2: Int) {

 val tmp = this[index1]

 this[index1] = this[index2]

 this[index2] = tmp

}

 

The 'this' keyword inside an extension function corresponds to the receiver object, the one that is passed before the dot. Now we can call such a function on any MutableList<Int> -


val abc = mutableListOf(1, 2, 3)

abc.swap(0, 2)

 


fun demo(x: Any) {

 if (x is String) {

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

 }
}

 


/* 	not explicitly defined */

fun main(args: Array < String > ) {

 val text = 10

 println(text)

}


/* 	explicitly defined 	*/

fun main(args: Array < String > ) {

 val text: Int = 10

 println(text)

}

 

 

Functional Programing makes Kotlin much more handier when it comes to collections -


fun main(args: Array < String > ) {

 val numbers = arrayListOf(15, -5, 11, -39)

 val nonNegativeNumbers = numbers.filter {
  it >= 0
 }

 println(nonNegativeNumbers)
}

Output - 15, 11

Higher - Order Functions are those functions that take functions as a parameter and also returns a function. Consider the following code:-


fun alphaNum(func: () -> Unit) {}

In the above code “func” is the name of the parameter and “ ( ) -> Unit ” is the function type. In this case, we are saying that func will be a function that does not receive any parameter and does not return any value also.

Lambda expression or an anonymous function is a “function literal”, i.e a function that is not declared, but passed immediately as an expression.

An Example of a Lambda Expression -


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

In the above example, we simply declare a variable ‘sum’ that takes two integers and adds them together and returns total as an integer.

Then we just use ‘ sum(2,2) ’ in order to call it. Pretty cool huh?

Anonymous Function is a function which allows us to specify the return type and in this, the function name is omitted. Consider the following example:-

Either this way -


fun(x: Int, y: Int): Int = x + y

or This Way


fun(x: Int, y: int): Int {

 return a + b

}


Clean Builds Building your Codebase first time

When we compile our Kotlin code first time,then it takes more time than Java. Java compilation is almost around 15-20% faster than Kotlin.


Phases of Incremental Builds

But as we know that Most of the time we need incremental builds like we are doing some modifications in our existing code and then building them and doing continuous deployment

So in that perspective, Kotlin takes same amount of time to compile as compared to Java and even little bit faster than Java.


The Future of Kotlin language

Kotlin interwork with Java and provdes incremental change of code and superior type system to Java and provides the easy Migration path from Java with backward compatability.

With features Like  more declarative, less code, mixed language database and more expressive than Java, Make Kotlin the future langauge for enterprises applications and Mobile. 


Concluding Kotlin vs Java

We know that clean build is done only one time in our project and I think Incremental Builds Compilation time are more crucial for us than Clean Build. So Kotlin is almost same as Java and yes we can go with Kotlin without worrying about Compilation time.

How Can Don Help You?

Don is a leading Software Company in Product Development and Solution Provider for DevOps, Big Data Integration, Real Time Analytics & Data Science.

Elixir Data - Modern Big Data Integration Platform

Elixir Data is a Modern Big Data Integration Platform that enables secure Data Pipeline With Data Integrity and Data Management. Elixir Data provides you with the freedom to work in desired Data Stack and Programming Language as it integrates well with NoSQL & Big Data Ecosystem, traditional databases, and business tools. Elixir Data provides the Public, Private or Hybrid mode of Code Deployment. Choose the cloud platform that suits your enterprise requirements.

Xenonify

Xenonify is an Enterprise Full Stack IoT Platform with Artificial Intelligence and Machine Learning. Xenonify offers Identify & Access Management, IoT Protocols, and Messaging,  Streaming & Real-Time Data Integration & Analytics for IoT Solution,  Real-Time Predictive and Preventive Intelligence, and  Microservices, Docker, and Kubernetes for the Internet of Things.