Getting Started with Kotlin Programming Language

Sachini Navodani
SachiniNP
5 min readMar 7, 2019

--

Kotlin is a modern open-source programming language which compiles to java bytecode. It is a safe, concise, interoperable and tool-friendly programming language. Kotlin is mainly inspired by the languages like Java, Scala and C#. Java and Kotlin are interoperable, so that we can call Java tasks from Kotlin and vice-versa. Kotlin is an Object Oriented language, but it is also a functional language.

Install Kotlin

You can install Kotlin using snap package. To install snap package first, the following command can be run.

sudo apt-get install snapd snapd-xdg-open

Then we can use the below command to install Kotlin.

sudo snap install — classic kotlin

Run ‘Hello World’ program on command line

Create a file including the following and save it as a Kotlin file using the .kt extension.

fun main() {
println(“Hello World!”)
}

Then you can compile the program using the Kotlin Compiler using the following command.

kotlinc HelloWorld.kt -include-runtime -d HelloWorld.jar

Here the -d indicates what is needed as the output of the compilation.In our case it is a .jar file. The -include-runtime makes the resulting .jar file self-contained and runnable by including the Kotlin run-time library in it.

Now we can run the program simply typing the following on command line and get the output.

java -jar HelloWorld.jar

Variables

var keyword is used to declare variables in Kotlin.

var name:String=”Sachini”

Constants

val keyword is used to declare constants in Kotlin.

val name:String=”Sachini”

Type Inference

In Java, there is no type inference mechanism. So it is needed to declare the type of functions and variables. But Kotlin can infer type automatically as it is a Statically Typed Language. A statically typed language knows the type of a variable at compile time where it is not needed to specify the type of variables like in Java and C based languages. So in order to declare a Long variable we can use val dpLong=123L, to declare a Float val dpFloat=76F, to declare a Hexadecimal val dpHexa=0x0F and likewise we can declare variables without specifying their type.

Kotlin Data Types

In Java, there are basically 2 data types they are primitive and non-primitive types. Java uses wrappers to make primitive types behave like objects. But in Kotlin, all the types are objects.

When we consider about numbers, Long(64 bit), Int(32 bit), Short(16 bit), Byte(8 bit) are integer types available in Kotlin. Double(64 bit), Float(32 bit) are the floating-point types.

The Boolean type of Kotlin is similar to Java and values can be true or false. Dis-junction (||), conjunction (&&) and negation (!) are the operations that can be performed on Boolean types as same as in Java.

String Interpolation

In Kotlin we don’t need to go for String concatenation. We can do String interpolation with the $ sign as in the below example code.

fun main() {
val price=70F
val fruit="Orange is $price rupees"
println(fruit)
val name="Sachini"
val msg="Length of name is ${name.length}"
println(msg)
}

Control Flow

Looping can be done using ranges in Kotlin using the in builtin operation. Below code snippet shows how to prints numbers in a particular range using the for loop.

for (i:Int in 10..20){
println(i)
}

Or we can print the loop as in the following by declaring the range using a constant before looping it.

val nums=20..30
for (i in nums){
println(i)
}

If we want to reverse the loop, it can be done as follows.

for (i in 10 downTo 1){
println(i)
}

We can loop a list as follows.

val pets=listOf("kitten","puppy","calf")
for (pet in pets){
println(pet)
}

Using while loop and do-while statement we can do the similar kind of things. Below code snippets print 9 to 0.

while

var a=10
while (a>0){
--a
println(a)
}

do-while

var b=10
do {
b--
println(b)
}while (b>0)

Kotlin allows us to break and continue from a loop at a certain point. It can be done as follow.

loop@for (i in 1..100){
for (j in 1..100) {
if (j % i == 0) {
break@loop
}
}
}

Conditional Statements

if-else

In Kotlin the if statement must have the else part, otherwise it generates an error. And in the if else statements only the last arguments of each if and else parts are passed. Warnings will be generated for the rest of the arguments. Here warnings are generated for both the “Human” and “Nothing”. Further we can pass any type of arguments(Strings, Ints, etc.).

fun main() {
var msg="Human"
val result=if (msg!=""){
"Human"
30
}else{
"Nothing"
40
}
println(result)

}

when

To check several conditions together we can use the when statement in Kotlin which acts more similar to switch operator of C-like languages.

fun main(){
val name="Man"
when(name){
"Man" -> {
println("AA BB")
println("aa bb")
}
is String -> println("CC DD")
}
}

Functions

Kotlin is a functional language, because it treats functions in first class. The ‘main’ function is the entry point for the Kotlin programs.

In Kotlin if there is no return type in a function, by default the return type is Unit. Unit is much similar to void in Java and it is a type with only one value and this value does not have to be returned explicitly.

fun hey():Unit{
println("Hey!")
}

So we can skip specifying the returning type and write the same function.

fun hey(){
println("Hey!")
}

A function that returns a value can be written eliminating its return type, because of the type inference of Kotlin.

fun returnANumber(){
return 8
}

Passing parameters to a function can be done as follows.

Single parameter

fun passName(name: String){
println(name)
}
fun main() {
passName("Abcd")
}

Multiple parameters

fun sum(a:Int,b:Int):Int{
return a+b
}
fun main() {
val valueSum=sum(7,2)
println(valueSum)
}

We can do this function declaration as a single line.

fun add(a:Int,b:Int)=a+b

Kotlin provides the special ability of making several parameters default.

fun adding(p:Int, q:Int,r:Int=0)=p+q+rfun main() {
val valueOfAdding1=adding(2,4,6)
println(valueOfAdding1)
val valueOfAdding2=adding(2,4)
println(valueOfAdding2)
}

Here we have assigned a 0 to r in declaration. So that the default value of r is 0 and we can either pass a value to r or just ignore. Naming parameters is significant when we have multiple default parameters, in order to know how we pass values to the default parameters and also to know the order of passing values.

In Java there are no default parameters, so we can have the same function call and overload it with different options in each, but Kotlin avoids us from function overloading.

Passing undefined number of parameters

fun studentNames(vararg strings: String){
reallyPrintStudentNames(*strings)
}

private fun reallyPrintStudentNames(vararg strings: String) {
for (string in strings) {
println(string)
}
}
fun main() {
studentNames("AA")
studentNames("AA","BB")
studentNames("AA","BB","CC","DD")
}

vararg allows us to create a function with unlimited number of arguments. Here spread operator (*) is used to pass the vararg type to the reallyPrintStudentNames() function.

--

--