Kotlin - Everything you need to know

Follow @desiprogrammer_

But what is Kotlin ?

Kotlin is a General-Purpose, static-typed programming Language , that is becoming extremely popular and widely used in the client side as well as server side. It's primirily being used in Android Apps, Jetpack-Compose and Kotlin MultiPlatform Mobile.

Code Playground

While writting apps and backend, we will obviously use Dedicated IDEs, but for simply experimenting and learning the language, we are going to use the Kotlin playground.

Simple Things to Know

1. A kotlin file has an extension of **.kt**.  
2. A kotlin program starts with main function.  
3. It is very similiar to Java.  
4. A kotlin Program doesn't need to always have a class, Like Java.
5. Kotlin Code Statements need not end with ;.

Hello World

We will use println to print a simple Hello World Program.

Man of culture

fun main() {
    println("Hello, world!!!")
}

Variables

Kotlin is a static typed language, so every variable has it's own type. we can declare a variable using the val or var keyword, followed by a vaiable name and it's value.

val myname : String = "Prince";

Type Inference

Since we assigned a value while declaring a variable, we need not to specify it's type, as Kotlin will get it by default.A feature known as Type Inference.

Val Keyword

It decalres a variable as a read-only variable. Which means the value can't be further changed.

fun main() {
    val myname = "Prince";
    myname = "A New Name"; // Val cannot be reassigned
    println(myname)
}

Var Keyword

It decalres a variable as a read-write variable.

fun main() {
    val myname = "Prince";
    myname = "A New Name"; // no error
    println(myname) // Prints A New Name
}

Data Type

In Kotlin, everything is an object, which means we can call member function and properties on any variable. Given below are some widely used Data Types.

- Int
- Float
- Double
- Boolean
- String

Strings

In kotlin too, Just like any other Language. A String is a combination of Characters that can be treated as an array, starting at index 0. Given below are some methods available for Strings.

fun main() {
    var myname = "Prince";
    myname = myname + " Programmer"; // concatnation
    println(myname.isEmpty()); // false 
    println(myname.length); // 17
    println(myname.substring(0,6)); // Prince
    println(myname.uppercase()) // PRINCE PROGRAMMER
    println(myname)
}

String Interpolation

To use or manipulate any variable in a string, we can use the String interpolation.

fun main() {
    var myname = "Prince";
    println(myname)
    // any type of variable can be used
    // this simply replaces the value
    println("I am $myname") // I am Prince
    // using {}, we can use expression
    println("I am ${myname.uppercase()}")   // I am PRINCE
}

Conditionals

Control Flow Structures such as if statements, if-else, switch, ternary operator.

if & if-else Statements

 if(expression){
     println("Statements")
 }
 
 // if-else
 if(x < 1){
     println("Statements")
 }else{
     println("Statements")
 }
 
 // they can also be nested
 // they can also be used as a ladder
 if(condition1) { 
     // code to run if condition is true
 }else if(condition2) {
     // code to run if condition is true
 }else{
     // code to run if none are true
 }

Switch Statement

Kotlin doesn't have a Switch statement, but the when keyword can be used to achieve something similiar.

Note : We will discuss about when later.

fun main() {
    val x = 12;
    when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { 
        // if none of the condition are met
        print("x is $x")
        }
    }
}

Ternary Operator

You can use the if statement as a ternary operator in the following way.

 val x = 12;
 if (x > 10) println("Greater than 10") else println("Less than 10");
 // if (expr) a else b;

Loops

Just like any other language, Kotlin provides us with loops to iterate through a collection or to do a task repeatedly.

For Loop

fun main() {    
    // for in range
    // default step is 1
    for(i in 1..10 step 2){
        println(i)
    }
    
    // to loop through array elements
    var myarr = listOf("Java","Python", "Dart");
    for(lang in myarr){
        println("I know $lang")
    }
}

In the same way we have while and do-while Loop too.

// while Loop
while (expression) {
    // codes inside body of while loop
}

// do-while Loop
do {
   // codes inside body of do while loop
} while (expression);

We also have break and continue statements, with the same meaning as usual.

Functions

Function is a group of related statements that perform a specific task. We use the fun keyword to define a function and then function name.

1. If a function does not return any useful value, its return type is Unit.
2. Kotlin supports local functions, which are functions inside another function.
3. Syntax

  fun functionName(parameter : parameterType) : returnType {
      // function body
  }
fun sayHello(){
    println("Welcome to Desi programmer !")
}

// Function Parameter
fun sayHello(name : String){
    println("Welcome from $name !")
    // `return Unit` or `return` is optional
}

// to call
sayHello("Prince)

Default Arguments

We can provide default values to parameters in function definition.

fun sayHello(name : String = "Prince"){
    println("Welcome from $name !")
}

// no parameter passed
sayHello()

Named Parameters

When calling a function, you can name one or more of its arguments. This may be helpful when a function has a large number of arguments, and it's difficult to associate a value with an argument, especially if it's a boolean or null value.

fun main() {
    // passing with name
    println(addEvenOddAndPrime(even = 6, odd = 9, prime = 7))
}

// the order to accept is wrong
fun addEvenOddAndPrime(even : Int,prime : Int, odd : Int){
    println("Even : $even");
    println("Prime : $prime");
    println("Odd : $odd");
}

Return Types

To return a value from a function, you must specify a return type after the function name.

fun main() {
    println(addNumber(12,13))
}

// here goes the return type
fun addNumber(a : Int, b : Int) : Int {
    return ( a + b);
}

Single Expression functions

When a function returns a single expression, the curly braces can be omitted and the body is specified after a = symbol:

fun main() {
    println(add10(12))
}

fun add10(a : Int) : Int = a + 10

Extension Function

Kotlin provides an ability to extend a class(also Int,String,Boolean or Lists) with new functionality without having to inherit from the class.

fun main() {
    println("prince".convertFirstCharToUpperCase())
}

fun String.convertFirstCharToUpperCase(): String {
    // The this keyword inside an extension function corresponds to the receiver object 
    return this[0].uppercaseChar() + this.substring(1)
}

Infix Notation

Functions marked with the infix keyword can also be called using the infix notation (omitting the dot and the parentheses for the call). Infix functions must meet the following requirements.

1. They must be member functions or extension functions.
2. All Infix functions are extension function but the reverse is not true.
3. They must have a single parameter.
4. The parameter must not accept variable number of arguments and must have no default value.
fun main() {
    // Infix function allows us to call function as value functionname param
    println(10 isGreaterThan 12)
}

infix fun Int.isGreaterThan(num : Int): Boolean {
    if(this > num) return true else return false;
}

Related..

Getting started with Jetpack Compose

Language Icon

How to Add Custom Fonts and Icons in Jetpack Compose ?

Language Icon