Categories: AndroidArticlesKotlin

Kickstarting with Kotlin

I am excited for Kotlin, want to know why? because it resembles Swift a lot. So it’s quite fun learning it. So let me start with a small introduction of Kotlin. We’ll go on to the syntax after that.

What is Kotlin?

Kotlin is a programming language which runs on Java Virtual Machine and is based on LLVM compiler infrastructure. Primarily, It was developed by the team of JetBrains developers based in St. Petersburg, Russia. Kotlin is design to interoperate with Java, just as you can do with Swift & Objective-C. Just like Java, The name Kotlin comes from an island situated near St. Petersburg. Recently Google adopted Kotlin as their official language for Android, which brought a sudden fame to it.

Data Types

The basic data types are Double, Float, Long, Int, Byte, Short, Character, Boolean and String. There are also literal constants such as Decimals, Hexadecimals and Binaries. and it has the rest of the Collections same as Java, but here Kotlin has also distinguished between mutable and immutable i.e collections that can be changed after initialization and those that can’t.

Syntax

If you’re coming from the background of Swift or TypeScript, declaring properties, writing methods and classes is quite similar to that.

Declaring Property

Declaring immutable properties

val a: Int = 1 
val b = "Kotlin" //Inferred String

and mutable properties like

var x : Int = 5

Commenting

Writing comments in Kotlin is not different than other languages.

// This is an end-of-line comment

/* This is a block comment
   on multiple lines. */

Writing a Functions and Classes

Prototype for writing a function is:

fun functionName(param: DataType):ReturnType{

}

//Sample function
fun sum(a:Int, b: Int): Int{
val c = a + b
return c
}

and defining a class goes this way:

class A{


}

interface B{

}

//Inheritance
class C : A(), B{


}

Control Flow

For Loops

There are a number of ways you can write for loops, syntax is as follows:

//1
for (item in items){
print(item)

}

//2
for (item: Int in ints) {
  // ... 
}

//3
for (i in array.indices) {
  print(array[i])
}

//4
for ((index, value) in array.withIndex()) { 
println("the element at $index is $value")
}

//5
for (i in 1..4){ 
print(i)
}

//6 Increment by any number other than 1
for (i in 1..4 step 2){ 
print(i) //prints "13"
}

//7
for (i in 4 downTo 1){ 
print(i) //prints "4321"
}

//8 Decrement by any number other than 1
for (i in 4 downTo 1 step 2){
print(i) //prints "42" 
}

If Statements

If statements can be written similarly as of any other language.

// Traditional usage 
var max = a 
if (a < b) max = b

// With else 
var max: Int
if (a > b) {
    max = a
} else {
    max = b
}
 
// As expression 
val max = if (a > b) a else b

If statements can also be held inside a variable.

val max = if (a > b) {
    print("Choose a")
    a
} else {
    print("Choose b")
    b
}

When Statements

Its like a Switch in other languages, can be written as follows:

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // Note the block
        print("x is neither 1 nor 2")
    }
}

//For multiple values
when (x) {  
0, 1 -> print("x == 0 or x == 1")  
else -> print("otherwise") 
}

Lambda

In Swift, Lambdas are known as Closure, in other languages they are also called Completion Handlers or Blocks. They can be passed as arguments in functions, and are really helpful while implementing Network classes, writing a lambda function is pretty straight forward. Here is a function which takes in two Integers and return the greater number in the block while the function is being called.

fun compare(a: Int, b: Int,completion:(greaterNumber:Int)->Unit){
    if (a > b){
        completion(a)
    }
    else{
        completion(b)   
    }
}

//Usage

var a = 1
var b = 7
compare(a,b,{ number ->
 print("$number is greater") //prints "7 is greater"
})

Extensions

It’s one of the useful feature of Kotlin, with this feature you can add further functions and properties to existing classes. Lets understand it by an example. Consider a immutable list.

val list = listOf(1,2,3,4)

And consider for some reason our program might access an index out of range from this list, for instance; a 5 or 6 and so on.

print(list[5])

Which will leave us with a runtime exception.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5

What we can do is write an Extension for the List, which will return a null value in case the index is out of range.

fun List<Int>.containsIndex(index:Int):Int? {
 if (this.contains(index)){
    return index    
    } 
    return null
}

//Usage
print(list.containsIndex(5)) //prints "null"

 

So, that was it for this tutorail. If you guys have any question please leave it in the comment section below.

Good Day! 🙂

Aaqib Hussain

Aaqib is an enthusiastic programmer with the love of Swift and anything that looks like Swift i.e Kotlin. He loves writing code in Swift, and exploring new technology and platforms. He likes to listen to old music. When he is not writing code, he's probably spend his time watching movies, tv-shows or anime, or either doing some research for writing the next article. He started Kode Snippets in 2015.

Recent Posts

Things to know when moving to Germany

This article covers some important things you must know when you are considering a move…

3 years ago

Unit Testing in Android for Dummies

What is Unit Testing? In its simplest term, unit testing is testing a small piece…

4 years ago

Factory Design Pattern

In this article, you will learn about a type of Creational Design Pattern which is…

5 years ago

Creating Target specific Theme in iOS

In this tutorial, you will go through the use of targets to achieve two separate…

5 years ago

Facade Design Pattern

In this article, you will learn about a type of Structural Design Pattern which is…

5 years ago

Singleton Design Pattern

In this article you will learn about a type of Creational Design Pattern which is…

5 years ago