opencodez

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 :

fun main(args: ArrayxStringx) {
  print("hello world")
}

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 :

package my.package.name

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.

import my.package.name.Dog //It imports ‘Dog’

Import my.package.name.* //it imports everything inside the package

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

Import my.package.name.Dog as d

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’. ‘valx is used for immutable variables and xvarx is used for re-assignable variables. The type of the variable is specified after the name. For example:

val name : String = "Alex" //can't be changed

var c : Char = 'a'

c = 'b' //can be changed

val sum = 20

Here, the first variable xnamex is a constant variable. The second variable xcx 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.

// This is a single line comment

/* This is a

multiline

comment */

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

Functions:

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

fun main(args: ArrayxStringx) {
  print(getMsg("Hello", "World"))
}

fun getMsg(firstWord: String, secondWord: String): String {
  return "$firstWord $secondWord"
}

In this example, xgetMsgx is a function that takes two parameters and returns one xStringx. Both parameters are of type xStringx. We are calling this function from the xmainx function.

If you run this program, it will print xHello Worldx as the output.

You can also write it like below:

fun getMsg(firstWord: String, secondWord: String) = "$firstWord $secondWord"

The result will be the same.

String Template:

The x$firstWord $secondWordx 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:

fun main(args: ArrayxStringx) {
   val count = 10
   print("The value of count is $count and the final msg is : ${getMsg("Hello", "World")}")
}

fun getMsg(firstWord: String, secondWord: String) = "$firstWord $secondWord"

It will print the below line as the output:

The value of count is 10 and the final msg is: Hello World

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

If expression:

Kotlin doesnxt have a ternary operation (condition ? then: else). In Kotlin, xifx returns a value i.e. it is an expression. We can use it with xelsex or as an expression:

fun main(args: ArrayxStringx) {
	var number = 10

	if(number%2 ==0){
		println("$number is even")
	} else {
		println("$number is odd")
	}

	var result = if(number%2 == 0) "even" else "odd"

	println("$result")

}

It will print:

10 is even

even

The first line is printed using an xif-elsex condition and the second line is printed using xifx as an expression.

for, while and do..while loop:

xfor loopx 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:

fun main(args: ArrayxStringx) {
  var vowels = listOf('a','e','i','o','u')
  for(c in vowels){
    println(c)
  }

  for(n in 1..3){
    println(n)
  }
}

It will print the below output:

a
e
i
o
u
1
2
3

xwhilex and xdo..whilex loops works similar to Java:

while(condition){

…..

}

do{

…..

}while(condition)

Kotlin also supports the xbreakx and xcontinuex operation in loops.

When Expression:

xwhenx expression was introduced to replace xswitchx operator in Kotlin. We can use a xwhenx expression to remove the dirty xif-else ifx chain.

fun main(args: ArrayxStringx) {
  val num = 0
  when(num){
    0,1 -x print("$num is 1 or 0")
    in 1..10 -x print("$num is in 1..10")
    else -x print("$num is greater than 0")
  }
}

You can try the above example with different values for xnumx. It will work the same as if-elseif-else statement. For example, if the value of xnumx is x0x, it will run the first xprintx statement. It will keep checking all the statements one by one and if all statements are failed, it will run the xelsex 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 xnullx but non-null reference canxt hold xnullx. For example :

var str: String = "Hello World"

This is a non-null reference. If we assign xnullx to xstrx, it will throw one compilation error. We can declare this variable as xString?x 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 xstrx, we can do that by either doing a xnull checkx using an xif conditionx, or by using a safe call or by using Elvis operator or with x!!x operator. For example :

fun main() {
  var str: String? = "Hello World"

  if(str != null){
    println("Check 1 : ${str.length} ") //if check
  }

  println("Check 2 : ${str?.length}") //safe call

  println("Check 3 : ${str?.length ?: -1}") //elvis operator

  println("Check 4 : ${str!!.length}") // !! operator

}

It will print x11x for all print statements. But if the value of xstrx is xnullx, the first statement will not execute, the second statement will print xnullx, the third statement will print x-1x and the fourth statement will throw one KotlinNullPointerException.

A comparison with 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.