KOTLIN Coding

Improving Versatile Arrangements & Calculations with KOTLIN

At Codelabpro, we make coding easier and enable learners with top-notch programming tutorials, courses, and resources. Whether you are a novice making your initial strides in coding or a seasoned developer aiming to improve your skills, we offer practical, real-world insights to assist you in achieving success.

Kotlin

Kotlin is a contemporary, open-source, statically typed programming language created by JetBrains. It is intended to interoperate with Java fully and is mainly utilized for creating Android applications, backend systems, and multiplatform projects. Kotlin is succinct, expressive, and safe, making it a favored option among developers.

Key Features:

  • Interoperability with Java: Kotlin is capable of using Java libraries and frameworks seamlessly.
  • Null Safety: Prevents null pointer exceptions (NPE) by design.
  • Concise Syntax: Minimizes boilerplate code.
  • Functional Programming: Facilitates functional programming paradigms.
  • Multiplatform Development: Develop applications that function on Android, iOS, Web, and Desktop.
Hello Zameer in Kotlin

Explanation:

fun: Keyword to define a function.

main: Entry point of a Kotlin program.

println: Prints text to the console.

 

fun main() {

    println(“Hello, Zameer!”)

}

 

1. Variables

Kotlin uses two keywords to declare variables:

  • val: Immutable variable (read-only).
  • var: Mutable variable (can be reassigned).
Explanation
  • val ensures name cannot be changed.
  • var allows age to be reassigned.

fun main() {

    val name: String = “Malik”  // Immutable

    var age: Int = 11           // Mutable

    println(“Name: $name, Age: $age”)

}

 

2. Functions

Functions in Kotlin are first-class citizens and can be concise.
Explanation

  • fun: Declares a function.
  • Parameters (a, b
  • return type (Int) are explicitly declared.

 

fun add(a: Int, b: Int): Int {

    return a + b

}

fun main() {

    val result = add(5, 3)

    println(“Sum: $result”)

}

3. Conditions and If Statements

You have previously discovered that C accommodates the standard logical conditions found in mathematics:
 
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
 
 

fun main() {

    val number = 5

    if (number % 2 == 0) {

        println(“$number is even”)

    } else {

        println(“$number is odd”)

   }}

  • Use if to indicate a section of code that should run, if a given condition is true
  • Use else to indicate a section of code that should run, if the same condition is false
  • Use else if to indicate a new condition to evaluate, if the initial condition is false
  • Use switch to indicate multiple alternative sections of code to be executed

int x = 20;

int y = 18;

if (x > y) {

  printf(“x is greater than y”);

}

4. Null Safety

Kotlin ensures null safety at compile time to avoid NullPointerException.

Explanation:

  • Adding ? after the type allows it to store null.
  • The safe call operator (?.) prevents crashes if the variable is null.

fun main() {

    var name: String? = null  // Nullable type

    println(name?.length)     // Safe call operator (?)

}

5. Classes and Objects

Kotlin is object-oriented, supporting classes, inheritance, and more.
A class consists of a collection of comparable objects. An object refers to a tangible entity, like a book, car, or similar items. A class is an abstract entity. An object is a concrete entity.

Explanation
 
class: Declares a class.
val and var in the constructor automatically create properties.
An object is created using the Person() class.

class Person(val name: String, var age: Int) {

    fun introduce() {

        println(“Hi, my name is $name, and I am $age years old.”)

    }}

fun main() {

    val person = Person(“Alice”, 25)

    person.introduce()

}

6. Collections

Kotlin supports both mutable and immutable collections.

Explanation

listOf: Creates a read-only list.

mutableListOf: Allows modifications.

  • Lists – Ordered groups of items that permit duplicates.
  • Sets – Unordered groups of distinct items.
  • Maps – Groups of key-value pairs, where each key is distinct.
  • Arrays – Collections of a fixed size with a defined type.
  • Sequences – Collections of items that are evaluated lazily and can be handled in a pipeline.


fun main() {

    val numbers = listOf(1, 2, 3)  // Immutable list

    val mutableNumbers = mutableListOf(4, 5, 6)  

// Mutable list

    mutableNumbers.add(7)

    println(numbers)

    println(mutableNumbers)

}

 

7. Lambda Functions

Kotlin supports concise lambda expressions for functional programming.

Explaination

  • val square: Declares a lambda function.
  • { number -> number * number }: Lambda syntax.
Functions in Kotlin are first-class entities and can be utilized as data types. Lambda expressions offer a concise syntax for writing functions. You can pass function types to other functions. You can also return a function type from another function. A lambda expression yields the result of the final expression.

fun main() {

    val square: (Int) -> Int = { number -> number * number }

    println(square(4))

}

 

8. Extension Functions

You can add new functions to existing classes.
Explanation
 
  • Extension functions enhance existing classes without modifying their source code.
 Kotlin extension functions enable a developer to “attach” methods to a class without inheriting from it or employing a design pattern. The extensions that are created function as regular methods within the class. Extension functions are defined with a prefix of the receiver type followed by the method name.

fun String.addExclamation(): String {

    return this + “!”

}

fun main() {

    println(“Hello”.addExclamation())

}

 
9. Coroutines (Asynchronous Programming)
Kotlin provides lightweight coroutines for asynchronous tasks.
 
Explanation
 
  • launch: Starts a coroutine.
  • delay: Suspends the coroutine for a given time.
On Android, coroutines assist in handling extended tasks that could otherwise obstruct the main thread and lead to your app becoming unresponsive.

import kotlinx.coroutines.*

fun main() = runBlocking {

    launch {

        delay(1000L)

        println(“World!”)

    }

    println(“Hello,”)

}