Kotlin

Kotlin is a modern and statically-typed programming language that runs on the Java Virtual Machine (JVM). Developed by JetBrains, Kotlin combines object-oriented and functional programming features, offering a concise and expressive syntax. It interoperates seamlessly with Java, allowing developers to leverage existing Java libraries and frameworks. Kotlin provides powerful language features like null safety, extension functions, coroutines for asynchronous programming, and data classes for easy object modeling.

Module 1: Introduction to Kotlin

Introduction to Kotlin

Kotlin is a modern statically typed programming language that runs on the JVM, Android, Browser, and Native.

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

Variables and Basic Data Types

In Kotlin, you can declare variables using either 'var' (mutable) or 'val' (immutable). Kotlin has several data types like Int, Double, Char, Boolean, and String.

val name: String = "John Doe"
var age: Int = 30

Control Flow

Kotlin offers several control flow constructs like if, when (equivalent of switch), for, and while loops.

val a = 5
val b = 10

if (a > b) {
	println("a is greater than b")
} else {
	println("b is greater than a")
}

Module 2: Functions and Classes in Kotlin

Functions

In Kotlin, functions are declared with the 'fun' keyword. Functions can have parameters and a return type.

fun add(x: Int, y: Int): Int {
	return x + y
}

fun main() {
	println(add(5, 3))  // Output: 8
}

Classes and Objects

Classes in Kotlin are declared using the keyword 'class'. An object is an instance of a class.

class Car(val brand: String, val year: Int)

fun main() {
	val car = Car("Toyota", 2020)
	println(car.brand)  // Output: Toyota
}

Module 3: Inheritance and Interface in Kotlin

Inheritance

Kotlin supports single inheritance, and a class can inherit from another class using the ':' symbol. By default, classes in Kotlin are final - they can’t be subclassed unless you mark the class with the open modifier.

open class Vehicle(val maxSpeed: Int)

class Car(maxSpeed: Int, val numberOfSeats: Int) : Vehicle(maxSpeed)

Interfaces

Interfaces in Kotlin are declared using the 'interface' keyword. They can contain definitions of abstract methods as well as method implementations. A class implements an interface using the ':' symbol.

interface Drivable {
	fun drive()
}

class Car : Drivable {
	override fun drive() {
		println("Driving a car")
	}
}

Module 4: Kotlin Null Safety

Null Safety

Kotlin is null-safe by default. It distinguishes nullable references from non-nullable ones. To denote nullability, a question mark '?' is appended to the type.

var a: String = "abc"
// a = null // compilation error

var b: String? = "abc"
b = null // ok