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 :
1 2 3 |
fun main(args: Array<String>) { 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 :
1 |
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.
1 2 3 |
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:
1 |
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’. ‘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:
1 2 3 4 5 6 7 |
val name : String = "Alex" //can't be changed var c : Char = 'a' c = 'b' //can be changed val sum = 20 |
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.
1 2 3 4 5 6 7 |
// 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:
‘fun’ keyword is used to define a function. It can take different arguments and returns a value just like Java functions. For example:
1 2 3 4 5 6 7 |
fun main(args: Array<String>) { print(getMsg("Hello", "World")) } fun getMsg(firstWord: String, secondWord: String): String { return "$firstWord $secondWord" } |
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:
1 |
fun getMsg(firstWord: String, secondWord: String) = "$firstWord $secondWord" |
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:
1 2 3 4 5 6 |
fun main(args: Array<String>) { 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:
1 |
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 ‘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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun main(args: Array<String>) { 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:
1 2 3 |
10 is even even |
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:
1 2 3 4 5 6 7 8 9 10 |
fun main(args: Array<String>) { 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:
1 2 3 4 5 6 7 8 |
a e i o u 1 2 3 |
‘while’ and ‘do..while’ loops works similar to Java:
1 2 3 4 5 6 7 8 9 10 11 |
while(condition){ ….. } do{ ….. }while(condition) |
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.
1 2 3 4 5 6 7 8 |
fun main(args: Array<String>) { val num = 0 when(num){ 0,1 -> print("$num is 1 or 0") in 1..10 -> print("$num is in 1..10") else -> print("$num is greater than 0") } } |
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 :
1 |
var str: String = "Hello World" |
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 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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 ’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.