Kotlin Language Basics – A Quick Reference Guide

Kotlin is a modern, concise, and powerful programming language that enhances productivity while ensuring clean and safe code.
This post covers core Kotlin concepts and provides resources, examples, and best practices for Android and general-purpose development.


📚 Kotlin Learning Resources


⚙️ Kotlin and Android Integration

Kotlin Android Extensions

apply plugin: 'kotlin-android-extensions'

Learn more: Kotlin Android Extensions

These are Android libraries written in Kotlin, primarily designed for Android app development by Google engineers.

Using Gradle with Kotlin

Documentation: Gradle for Kotlin


🧩 Extension Functions

Extension functions allow developers to add new functionality to existing classes.
Watch this video for an introduction: Kotlin Extension Functions Explained

They are commonly used, reusable, and well-tested utility functions created by the Kotlin team.

Example: Extension Function Demo


🧠 Core Language Concepts

Inline Functions

  • Code insertion happens at compile time
  • Improves clean code and performance

Lambda Functions

  • Anonymous functions enclosed in { }
  • Can be passed as arguments or returned from functions

Constants and Variables

KeywordDescription
constValue known at compile time — no runtime overhead
varMutable variable — can be reassigned
valImmutable variable — value cannot change once assigned
letExtension function that takes a lambda as argument

💤 Lazy and lateinit Initialization

Kotlin supports delegated properties — properties whose values are computed or initialized lazily.

Lazy

  • Initialized only when accessed
  • Example of lazy loading: val data by lazy { fetchDataFromNetwork() }

Lateinit

  • Used for non-null properties initialized later in code, often inside init{} blocks. lateinit var username: String

🏗️ Constructors in Kotlin

  1. Primary Constructor – Mandatory; declared in class header.
  2. Secondary Constructor – Optional; declared using the constructor keyword.
  3. Init Block – Executes immediately after the constructor runs.

Example:

class Person(val name: String) {
    init {
        println("Person initialized with name $name")
    }
}

Note: Kotlin does not use the new keyword.
Example:

val human = Man()

All classes in Kotlin inherit from the Any superclass (similar to Object in Java).


🎯 Higher-Order Functions & Closures

  • Higher-order functions take another function as an argument or return one.
  • Closures allow inner functions to access variables from the outer function.

Example:

fun outer() {
    var x = 3
    fun inner() {
        println(x)
    }
    inner()
}

🔢 Data Types in Kotlin

Kotlin has no primitive types — everything is an object.

TypeSizeExample
Byte1Bvar b: Byte = 1
Short2Bvar s: Short = 10
Int4Bvar i = 100
Long8Bvar l = 100L
Float4Bvar f = 3.14F
Double8Bvar d = 3.14

Notes:

  • Strings & Numbers are immutable (call by value)
  • _ can be used for numeric readability: 10_000

⚡ Null Safety

Two main ways to handle nulls:

var a: Int? = null  // Nullable Int
var b: Int = null   // ❌ Compile error

Operators:

  • ? → Safe call
  • ?: → Elvis operator (default value if null)
  • !! → Throws exception if object is null

🔁 Ranges and Conditional Logic

Range Example

val a = 100
if (a in 101..1000) println("In range") else println("Out of range")

When Expression (like Switch)

val a = 101
when (a) {
    0 -> println("Zero")
    100 -> println("Hundred")
    in 100..1000 -> println("Between 100 and 1000")
    else -> println("Not in range")
}

🧮 Standard Library Functions

Creating Arrays and Lists

val arr = Array(4) { it * 2 }  // [0, 2, 4, 6]
val alphabets = arrayOf('a', 'b', 'c', 'd')
println(alphabets.asList())    // [a, b, c, d]

🔂 For Loops in Kotlin

Case 1: Iterate through array

val alphabets = arrayOf('a','b','c','d')
for (i in alphabets) {
    println(i)
}

Case 2: Character range

for (i in 'a'..'d') {
    println(i)
}

Case 3: Using index and element

for ((index, element) in alphabets.withIndex()) {
    println("index=$index, element=$element")
}

⚗️ Functional Programming Helpers

Apply(), Let(), and Custom Functions

Custom Extension + Higher-Order Function

Triple and Pair


🧩 Operator Overloading Example

Example: View on Kotlin Playground

println(2.plus(71).plus(233).minus(13).div(30).plus(1))

✅ Summary

Kotlin offers:

  • Clean, concise, and null-safe syntax
  • Easy Java interoperability
  • Functional programming support
  • Built-in extensions and high-order functions

Whether you’re developing Android apps, cross-platform mobile apps, or server-side applications, Kotlin gives you the balance between expressiveness and power.


Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top