What is Kotlin?

Google has announced Kotlin as a official language for Android Application Development in Google I/O 2017. Google surprised all android developers by this announcement. Than many developers has started work with Kotlin and fall in love with its concise syntax and safety. I am one of them.

Kotlin is a statically-typed language, developed by Jetbrains. With features like higher-order functions, lambda expressions, operator overloading, string templates, and more, Kotlin has a lot more to offer than Java. Because Java and Kotlin are highly interoperable, they can be used together in the same project.

Every programmer knows that for learning any programming language we need to learn syntax of that language and basics of that language like variables, conditional statements, functions. Here in this blog we will learn basics of Kotlin language.

How Kotlin works with Android?

Kotlin and JVM

 

How to declare variables in kotlin?

Variables can be declare using ‘val’ and ‘var’ keyword in kotlin. Now question is what is difference between ‘val’ and ‘var’.

1). val: val is same as the final modifier in java. As you should probably know that we can not assign to a final variable again but can change its properties. so Val is used to declare immutable variable.

Example:

val str:String = "Hello"

// now if you try to reassign value to "str"
str = "World" // this will show you error "val cannot be reassigned"


2). var: we can change the value of variable which is declared using ‘var’ keyword. So var is used to declare mutable variable.

Example:

var str:String = "Hello"
//we can change value of “str” if it is defined using ‘var’ keyword.
str = "World" //This will not generate any error


Some more examples for variable declarations:

val a: Int = 1 // readonly value
var x = 5 // `Int` type is inferred
var isSelected = false // Boolean variable
var isSelected:Boolean = false


Conditional statements:

If..else:

Kotlin if else ladder when

Example:

1. Simple If case:

var isSearching=false
    if(!isSearching)   isSearching=true

2. if else:

var maxValue: Int
val pValue=10
val qValue= 20
if (pValue> qValue) {
    maxValue = pValue
} else {
    max = qValue
}

 

Make a note that if you try to assign value to variable using if expression than compulsory you have to add else branch.

Note: Kotlin not support ternary operator (condition ? then : else) because kotlin if expression works fine in this case also.

Example:

val greater=If(10>20) true else false

 

When expression:

> When expression in kotlin has replace “Switch Case” which we are using in java and C like language. It matches its arguments with all branches sequentially until some branch condition is satisfied. Here, we can use when expression as a statement or as a expression. If it is used as an expression, the value of the satisfied branch becomes the value of the overall expression. If it is used as a statement, the values of individual branches are ignored(same as if condition).

Example:

private fun getRandomNumberInRange(min: Int, max: Int): Int {
    if (min >= max) {
        throw IllegalArgumentException("max must be greater than min")
    }
    val r = Random()
    return r.nextInt(max - min + 1) + min
}
var mNumber=getRandomNumberInRange(0,10)

1). Simple when expression:

when(mNumber){
	0-> print(“Number = 0”)
	1-> print(“Number = 1”)	
	else-> {
		print(“Number = None”)
	}
}

Here else is same as default case in Switch statement. If when is use as expression than else in mandatory.

2). when with range or collections:

when(mNumber){
	0..5-> print(“Number = 0”)
	6-> print(“Number = 1”)	
	else-> {
		print(“Number = None”)
	}
}

3). When using branch combined with comma:

when(mNumber){
	0,1,2,5-> print(“Number = 0”)
	6-> print(“Number = 1”)	
	else-> {
		print(“Number = None”)
	}
}

4). When using smart cast:

fun getGender(isMale:Any)=when(isMale){
is True-> “Male”
Else-> “Female”
}

5). We can also replace when instead of if else if chain:

when(mNumber){
	mNumber.isOdd()-> print(“x is odd”)
	mNumber.isEven()-> print(“x is Even”)
	else->print(“x is not a Number”)
}

For Loop:

> For loop in kotlin is equivalent to the foreach loop.

Syntax:

for (item in collection) print(item)

Example:
for(I in 1..10){
     println(i)
}

//With array
for(i in arrayNumber.size){
     println(arrayNumber[i])
}

While loop:

while and do..while work as usual

while (x > 0) {
    x--
}

do {
    val y = retrieveData()
} while (y != null) // y is visible here!

Hope you like this blog. If you have any question please ask me in comments or you can message me on twitter and facebook also.

Summary

Popularity of kotlin is getting increase day by day. More people are now learning kotlin for android development and most of them giving positive reviews. Most important point is Kotlin is designed with Java Interoperability in mind which makes it unique and easy to learn.

https://android4dev.com

Hi, I am Android Developer and Founder of Android4Dev. Right now my interest is in RxKotlin, MVVM and Dagger2. I am Kotlin Lover. Kotlin made me more productive in terms of coding. Do you want me to code for you ? Please don’t hesitate to contact me.