Basics of Kotlin for Android Development

Basics of Kotlin for Android Development

saurabh jadhav's photo
saurabh jadhav

Published on Aug 27, 2021

4 min read

Subscribe to my newsletter and never miss my upcoming articles

Hey So we will start with Iconic Hello world !

Hello World

fun main(){
    println("Hello world")
}
Out:
Hello world

So is as simple as that, Now println() is used for next line.

print("Hello")
//next print will continue prining withought next line
print("saurabh")

Out:
Hellosaurabh

//So with println next line will be used 
println("Hello")
println("Saurabh")

Out:
Hello
Saurabh

Functions

fun mm(){
    //fun is used to declare a function
    println(2)

}

For calling function Of course we have to define in main()

Example:

fun mm( ){
    println(2)

}
fun main()
{
mm()
}

Out:
2

Passing Arguments

fun mm( x: String){
    println(x+x+2)
    //yes concatenation works too ! 
}

fun main()
{   mm("Hello") 
//It will print--> HelloHello2   
}

Defining return type

fun main()
{
    print(add(2,3))

}

fun add(a:Int,b:Int):Int{ 
    //here we have set return type as Int
    //return type is preceeded by ':'
    return  a+b
}

Out:

5

Single Line Fun()

fun main()
{
    print(add(2,3))

}

fun add(a:Int,b:Int):Int=a+b //isnt it good?
Out:
5

Default Parameters

fun main()
{
greetings("Good morning")
    greetings() //default will be used
}

fun greetings(greet: String="olllala"){
    //we assigne "Olalla" for default if no args is passed
    println("Hello $greet")
}

Out:
Hello Good morning
Hello olllala //default is used

Variables

var number = 42var message = "Hello"

So here number is of type Int and message is of String

Type is automatically detect by type of data we put into variable.

But in var number , we cant put String or other type of datatype in future.

Read Only Variables

val message = "Hello"val number = 42//The value of variable define with val cant be reassigned

Constants

const val x = 2//note u cant define constant inside class decalration

Specifying data Type explicitly

val x:String="Hello Saurabh"//by using colon and following with datatype

It is useful when you are using multiple classes.

Using variable in Print

Use $ sign here.

fun main(){    var a="Saurabh"    println("Hello $a")}Out:Hello Saurabh

Expressions:

Use curly brackets for operations.

fun main(){    var a=10    var b=20    println("Hello ${a+b}")}Out:Hello 30

Null Safety

var neverNull: String = "This can't be null"            neverNull = null                                        var nullable: String? = "You can keep a null here"      nullable = null

You have to add ? so it can store null.

Conditions

If/else

if else is normal like other languages .

fun main(){    a=10    if(a<12)    {        println("a is smaller than 10")    }    else{        print("Olllala")    }}

For elif like python - use Else if

If you wrote block in one line then no need to use curly brackets but if used then its good.

Ternary

val result = if (condition) trueBody else falseBodyEg:fun main(){    var op= if(2<10) print("Yes") else print("Nonsense")    println(op)}

When -its like Switch case

   var x="Saurabh"    when(x){        "Saurabh"->{            print("Its saurabh")        }        "Hello"->{            print("its Hello")        }        else->{            print("Default")        }    }    Out:    Its saurabh

So you got? Just add -> this symbol “One hyphen followed by arrow”

while else is like default in Switch case.

Collections

ListOf

  var strings= listOf("abc","def","ghj")//you can pass combo of number and strings also        print(strings)  Out:  [abc, def, ghj]

If you want to pass data of only certain type then explicity define it

Eg:

 val names= mutableListOf<String>("hello",1)    print(names)Out://It will give error//Kotlin: The integer literal does not conform to the expected type Stringval names= mutableListOf("hello",1)    print(names)Out:[hello, 1]

Map

Its like an dictionary in python

var map= mapOf("a" to 1,"b" to 2,"c" to 3 )        print(map)Out:{a=1, b=2, c=3}

In map to is in internal function which creates pair of both.

SetOf

var set= setOf("abc","def","ghj")        print(set) Out: [abc, def, ghj]

Note:

IN kotlin this collection we define above are by default immutable

if we want to change data we can’t so we can define by saying mutableListOf()

So it will be mutable list.

Control flow

For loop

  val name= arrayOf("av","def","sd")  for(n in name){        println(n)    }Out:avdefsd

Loops are like Python…or like for each like java

While and Do-while works normally like other languages

Ranges

    for (i in 0..3)//it is like again  python but it will print 3 also    {        println(i)    }Out:0123

Char Support:

   for (c in 'a'..'d') {             println(c)    }    Out:abcd

Other Option for ranges:

Until:
 for (i in 0 until 2)    {        println(i)    }Out:01
Step:
 for (i in 0..5 step 2)//It will jump or skip 2 iterations or values    {        println(i)    }Out:024
 
Share this