A Beginners Guide to Kotlin

What is Kotlin ?

Kotlin is an expressive Open Source Programing Language with Type Interface for Android development which supports Java Virtual Machine. Google has adopted Kotlin as an official language for Android development.

Kotlin development was started by JetBrains initially. It is a compiled and statically typed programming language. Kotlin can be compiled to many different platforms including Java Virtual machine.  We can even use Java code and libraries with a Kotlin project.

Its popularity is growing day by day, especially among Android developers. It is similar to swift and that makes it easy for an iOS developer to switch to Android development and vice versa. Even Google has declared it as an official language for Android and provides full support on Android Studio.

Kotlin can be used to develop different types of applications. You can create Android applications using kotlin, graphical applications, web applications or even you can develop iOS applications as well. Kotlin team has started one experimental feature called Kotlin multi-platform that allows you to develop one application on iOS, Android, Desktop, Browser JavaScript or in any platform with single shared source code.

In this article, I will give an overview of Kotlin and walk you through the basics of Kotlin.

Writing your first program :

Kotlin provides an online code editor to try kotlin code. Open the editor in a browser and paste the below code :

Now, run the program. It will print “hello world” as the output. In this program, ‘main’ is a function. It takes optional ‘args’ arguments. We can pass arguments to this function using a command line. The ‘print’ statement is used to print something on the terminal. This is the start point of any Kotlin class. If you have this ‘main’ function, it will be called always at first.

This is similar to the main function in a Java class, but the code is more concise.

Packages:

The concept of ‘package’ is same as like Java. A class may start with the declaration of a package like :

Everything declared in a class are contained inside a package. We can import a single class or the contents of a package, class or scope using the ‘import’ statement.

We can also use ‘as’ keyword to change the name of the imported entity:

Note that the package name of a class file is not required to match with its directory location.

Using variables:

Kotlin uses two keywords for defining variables: ‘val’ and ‘var’. ‘val’ is used for immutable variables and ‘var’ is used for re-assignable variables. The type of the variable is specified after the name. For example:

Here, the first variable ‘name’ is a constant variable. The second variable ‘c’ is not. We can change its value. The third variable is a constant variable but note that we are not defining the type while declaring. Kotlin can automatically detect the type.

Comment:

Kotlin supports both single line and multi-line comments.

The single line comment can be used at the end of a line.

Functions:

‘fun’ keyword is used to define a function. It can take different arguments and returns a value just like Java functions. For example:

In this example, ‘getMsg’ is a function that takes two parameters and returns one ‘String’. Both parameters are of type ‘String’. We are calling this function from the ‘main’ function.

If you run this program, it will print ‘Hello World” as the output.

You can also write it like below:

The result will be the same.

String Template:

The “$firstWord $secondWord” string in the above example may be unfamiliar to you. This is called a string template. A string template is used to embed the result of an expression in a string. It starts with a dollar sign. We can include a single variable or a complex expression in a string template. For example:

It will print the below line as the output:

Here, we are creating the above string by including the value of ‘count’ and the result of ‘getMsg’ function. For using a string template with an arbitrary expression, curly braces are required.

If expression:

Kotlin doesn’t have a ternary operation (condition ? then: else). In Kotlin, ‘if’ returns a value i.e. it is an expression. We can use it with ‘else’ or as an expression:

It will print:

The first line is printed using an ‘if-else’ condition and the second line is printed using ‘if’ as an expression.

for, while and do..while loop:

‘for loop’ can iterate through anything that returns an iterator. We can iterate through a list of items or we can iterate through a range of numbers using range expression like below:

It will print the below output:

‘while’ and ‘do..while’ loops works similar to Java:

Kotlin also supports the ‘break’ and ‘continue’ operation in loops.

When Expression:

‘when’ expression was introduced to replace ‘switch’ operator in Kotlin. We can use a ‘when’ expression to remove the dirty ‘if-else if’ chain.

You can try the above example with different values for ‘num’. It will work the same as if-elseif-else statement. For example, if the value of ‘num’ is ‘0’, it will run the first ‘print’ statement. It will keep checking all the statements one by one and if all statements are failed, it will run the ‘else’ statement.

Null safety:

Null-safety is one of the important features of Kotlin. This was introduced to eliminate NullPointerException from code. We can categorize the reference into two parts: nullable reference and non-null reference. Nullable reference can hold ‘null’ but non-null reference can’t hold ‘null’. For example :

This is a non-null reference. If we assign ‘null’ to ‘str’, it will throw one compilation error. We can declare this variable as ‘String?’ to make it a nullable reference. But in this case, we need to check if the value is null or not before accessing any property of the variable. Suppose we want to check the length of the variable ‘str’, we can do that by either doing a ‘null check’ using an ‘if condition’, or by using a safe call or by using Elvis operator or with ‘!!’ operator. For example :

It will print ’11’ for all print statements. But if the value of ‘str’ is ‘null’, the first statement will not execute, the second statement will print ‘null’, the third statement will print ‘-1’ and the fourth statement will throw one KotlinNullPointerException.

A comparison with Java:

  • Java requires to write more code as compared to Kotlin. This increases the chance of errors and bugs.
  • Kotlin is more easy to understand. Any beginner programmer will find it easier to learn than Java.
  • We can write null safety code in Kotlin, which is not possible in Java without using a lot of ‘if-else’ conditions.
  • Kotlin is a new language and the community and information are limited as compared to Java.

Kotlin has both advantages and disadvantages if we compare it with Java. But the adoption is growing day by day and it will bring a lot of benefits in the future. If you are a beginner programmer or a Java android developer or a swift iOS developer, it makes sense to try Kotlin.

Add a Comment

Your email address will not be published. Required fields are marked *