ZOFTINO.COM android and web dev tutorials

Kotlin Basics Tutorial

In this tutorial, you can learn basic elements of kotlin programming language. You can use eclipse or intellij idea for developing kotlin applications.

Table of Contents

Kotlin File

Kotlin program file is saved with kt extension. You can define functions and classes in it. It can contain multiple classes. In the kotlin file, the first statement is package statement which declares the package to which the file belongs to.

package com.zoftino.coupon.kotlin

Next, it contains import statements for the classes or functions which are used in the file. By default, certain packages from kotlin library are imported, for example primitive data type classes, collections, etc.

import kotlin.math.nextDown

Defining Variables

To declare variable in kotlin, you need to use val and var keywords. The keyword val is used to declare constants meaning in the declaration you assign a value to the variable and the variable can’t be reassigned.

	var store = 3
	val category = 2
	
	println("var  "+store)
	println("val  "+category)	
	
	store = 6	

If you reassign a value to category variable declared using val, you will get compiler error Val cannot be reassigned.

category = 4

Variables are declared without specifying the data type, that is because kotlin compiler infers the data type using data assigned to the variable. Following code shows how to specify data type in the variable declaration statement.

	var deal : String
	var discount : Int = 20

If you don’t assign a value to a variable in the definition, you must specify the data type.

Data Types

Unlike java, there are no primitive types in kotlin, meaning all types are classes. Basic data types in Kotlin are Int, Long, Short, Float, Double, Char, Boolean, String and Array.

Here is an example of using data types, it also shows invoking on data type object various methods such as plus, minus, times, div, rem, toInt, toChar, nextDown, nextUp and roundToInt.

var price : Double
price = 33.3

println(price.plus(4))
println(price.minus(2))
println(price.times(10))
println(price.div(10))
println(price.rem(3) )
println(price.toInt())
println(price.toChar())
println(price.nextDown())
println(price.nextUp())
println(price.roundToInt())

Output:

37.3
31.299999999999997
333.0
3.3299999999999996
0.29999999999999716
33
!
33.29999999999999
33.300000000000004
33

Here is how a string variable is defined in kotlin.

val name = "kotlin"

In ktolin, string can contain template expression.

var discountAmount = 200
val coupon = "get upto $discountAmount off on fashion"
println(coupon)

Output:

get upto 200 off on fashion

Arrays

To define arrays in kotlin, you need to use Array class which provides various methods such as get, set, size, indexOf, sortedDescending, all stream functions, etc.

You can create array using arrayOf library function as shown in the following example. It create array of strings.

val cat = arrayOf("electronics", "fashion", "luggage", "appliance", "home")

println("number of categories: "+cat.size)
println("category at index 2 is: ${cat.get(2)}")

cat.set(2, "kitchen")
println("category at index 2 is: ${cat.get(2)}")

println("index of fashion: "+cat.indexOf("fashion"))
println("sorted descending: "+ cat.sortedDescending().toString())

var catReverse = cat.reversedArray()
val catCopy = cat.copyOf()
val catClone =  cat.clone()

Output

number of categories: 5
category at index 2 is: luggage
category at index 2 is: kitchen
index of fashion: 1
sorted descending: [kitchen, home, fashion, electronics, appliance]

Array can be created using Array class by passing size and function which returns element for each index as shown in the following example. The example uses when control flow on which you can find details in the following sections.

val brands = Array(4, { i ->
        when (i) {
            1 -> "Apple"
            2 -> "Samsung"
            3 -> "Moto"
            4 -> "Panasonic"
            else -> "LG"
        }

    })
println("Brand at index 2 is: ${brands.get(2)}")

Output

Brand at index 2 is: Samsung

If you want to create an array of primitive types, you can use IntArray, BooleanArray, ByteArray, CharArray, DoubleArray, FloatArray, IntArray, LongArray or ShrotArray classes.

val marks = intArrayOf(66, 75, 87,49)

See control flow section to learn how to iterate arrays in kotlin.

Defining Functions

In kotlin, a function is defined using fun keyword followed by name of the function and then parameters in the parenthesis then return type and body of the function. Functions doesn’t have to be part of classes, you can define functions in kotlin file like classes are defined. Functions can be defined inside another function; such functions are called local functions. Functions can be defined inside a class, which are called member functions

Following function takes string as argument and returns integer.

fun getDiscount(coupon: String): Int {
    val pIndex = coupon.indexOf('%')
    val discStr = coupon.substring(pIndex - 2, pIndex)

    return discStr.toInt()
}

Here is how a function is called in kotlin.

fun main(args: Array<String>) {
   val disc = getDiscount("get upto 30% off on mobiles");
    println("coupon discount percentage is $disc")
}

Output

coupon discount percentage is 30

If a function returns a value and contains only one expression, then we don’t need to use curly braces to define body of the function.

fun main(args: Array<String>) {
    println(calculateDiscount(4860.40))
}
fun calculateDiscount(orderAmt: Double) : Double = orderAmt*10/100

You can assign to function parameters the default values which are used when no values are passed to the function.

fun main(args: Array<String>) {
   println(getTaxAmount(1234.88))
   println(getTaxAmount(1234.88, 18))
}
fun getTaxAmount(orderAmt : Double, tax : Int = 10) : Double{
    return orderAmt*tax/100
}

Output

123.48800000000001
222.27840000000003

Calling a Function from a Kotlin File in Different Package

To call a function defined in a different package, the function needs to be imported in the kotlin file where is called.

Here is a function defined in one package.

package com.zoftino.cashback

fun getCashbackOffers() : String {
    return "upto 2% cashback"
}

Called from different package.

package com.zoftino.offer

import com.zoftino.cashback.getCashbackOffers
fun main(args: Array<String>) {
    println(getCashbackOffers())
}

If Else

Here is an example of if else control flow statement in kotlin.

fun getCouponByCategory(dicCat: Int): String {
    var discountPercentage: Int
    if (dicCat == 1) {
        discountPercentage = 50
    } else {
        discountPercentage = 80
    }

    return "get upto $discountPercentage% off on all items"
}

In kotlin, if else can be used as an expression because it returns a value. Last statement from the if else blocks is returned as value. Following examples shows how to use if else as an expression in kotlin.

val category = "fashion"
var base : Int

val discount = if(category.equals("mobiles")){
    base = 3
    base * 10
}else{
    base = 4
    base * 12
}
println(discount)

When

Similar to switch in java, you can use when control flow statement in kotlin.

fun printCategoryDiscount(category: String) {
    when(category){
        "electronics" -> println("electronics :"+20)

        "appliances" -> println("appliances :"+30)

        "sports" -> println("sports :"+60)

        "fashion" -> println("fashion :"+50)
    }
}

Call the function passing a value to it.

fun main(args: Array<String>) {
    val category = "appliances"
    printCategoryDiscount(category)
}

Output:

appliances :30

Unlike switch in java, you don’t need to use break statement in each case as the next statement after the when block gets executed after executing the matching case in when.

You can add default case to when using else as shown below. Default case gets executed if none of the case statements is matched.

val userChoice = 3
when(userChoice) {
    1 -> println("choice one")
    2 -> println("choice two")
    else ->   println("default choice")
}

Output

default choice

Similar to if else statement, when can also be used as statement or expression. In the expression form, when assigns to a variable the value from the matching case block as shown in the following example.

val store = "amazon"
val numCoupon =  when(store) {
    "amazon" -> 20
    "walmart" -> 30
    "sears" -> 10
    else ->   50
}
println("number of coupons for $store is $numCoupon")

Output:

number of coupons for amazon is 20

You can combine branch or case conditions by separating them with comma, as shown in the following example

val loanType = "personal"
when (loanType){
    "home" -> println("home loan interest 5%")
    "personal", "student"-> println("personal or student loan interest 7%")
    "car" -> println("car loan interest 3%")
}

Output

personal or student loan interest 7%

Branch or case condition can be an expression which returns value as shown in the following example

val taxBracketAmt = 500
val baseOrderAmount = 4000
when(taxBracketAmt) {
    baseOrderAmount/2 -> println("tax: 30%")
    baseOrderAmount/4 -> println("tax: 20%")
    baseOrderAmount/8 -> println("tax:  15%")
    else ->   println("default tax : 10%")
}

Output:

tax:  15%

Branch condition can be a check to find out the given value to when is in a range or a collection using in or !in operators.

val catType = 5
when (catType){
    in 1..5 -> println("it is one of the fashion categories")
    in 6..10 -> println("it is one of the electronic categories")
    !in 1 ..15 ->  println("it is one of the other categories")
}

Output:

it is one of the fashion categories

Branch condition in when statements can be a check to find out the type of the given value to when, following example shows how to find the type of the given value using is operator

var input = 10
when (input){
    is Int -> println("half of the given int val is: "+input/2)
    else -> println("the given value is not int")
}

Output:

half of the given int val is: 5

When control flow in kotlin can be used as if else chain as shown in the following example

val orderAmt = 400
when {
    orderAmt > 800 -> println("order is eligible for 15% discount")
    orderAmt > 400 -> println("order is eligible for 8% discount")
    orderAmt > 200 -> println("order is eligible for 4% discount")
    else -> println("order is not eligible for any discount")
}

Output

order is eligible for 4% discount

For Loop

In kotlin for loop allows for iterating range of numbers, arrays, collections and anything which provides iterator. Following example show how to use for loop with an array.

val employeeIds = intArrayOf(466, 795, 237,1239)

for(employee : Int in employeeIds)
    println(employee)

Output

466
795
237
1239

Following example shows how to use for loop with range of numbers.

val couponCat = 1..4

for(cpCat in couponCat){
    println("fetching coupons for coupon category $cpCat")
    println("fetching is done")
}

While Loop

Here are while and do while loops examples.

val ticketType =  arrayOf("bus", "train", "flight", "cruise")
var i = 0
while(i < ticketType.size){
    println("number of available tickets in "+ticketType[i]+" is "+i*2)
    i++
}

Output

number of available tickets in bus is 0
number of available tickets in train is 2
number of available tickets in flight is 4
number of available tickets in cruise is 6

Do while loop example. This example tries to perform an action, if it is successful it will exit the loop, otherwise it will try to perform the same action 3 times.

The example uses break statement to exit the loop. Similarly continue statement can be used in loops.

var actionCount = 0
do{ 
    println("fetching data from remote source")

    val success : Long = 1
    if(Math.round(Math.random()) == success)
        break

    actionCount++
}while (actionCount < 4)

Return Labels

You can use labels with break, continue and return statements to define where to start execution after those statements.

For example with following function, execution is returned to main function after return statement in the function.

fun main(args: Array<String>) {
    getStores()
    println("got stores from remote source")
}
fun getStores(){
    listOf(1, 2, 3, 4).forEach {
        println("getting stores info try $it")

        if(it == 2){
            return
        }
    }
    println("stores fetched")
}

Output

getting stores info try 1
getting stores info try 2
got stores from remote source

But if you define a label after forEach operation as shown in the following example, return statement causes the execution to continue with the next element from the list.

fun getStores(){
    listOf(1, 2, 3, 4).forEach stores@{
        println("getting stores info try $it")

        if(it == 2){
            return@stores
        }
    }
    println("stores fetched")
}

Output

getting stores info try 1
getting stores info try 2
getting stores info try 3
getting stores info try 4
stores fetched
got stores from remote source