Kotlin language

Rahul Chaube
3 min readAug 24, 2024

--

C

# Kotlin Notes

## 1. **Introduction to Kotlin**
Kotlin is a statically typed programming language developed by JetBrains. It is fully interoperable with Java and is used for Android development, server-side development, and more.

### Key Features:
- Concise syntax
- Safe null handling
- Extension functions
- Coroutines for asynchronous programming
- Interoperability with Java

## 2. **Basic Syntax**

### Hello World Example
```kotlin
fun main() {
println(“Hello, World!”)
}
```

### Variables
Kotlin supports two types of variables:
- **Immutable (read-only) variables** using `val`
- **Mutable variables** using `var`

```kotlin
val name: String = “Kotlin”
var age: Int = 10
```

### Data Types
- **Primitive Types:** `Int`, `Double`, `Float`, `Boolean`, `Char`
- **Special Types:** `String`, `Array`

```kotlin
val number: Int = 42
val pi: Double = 3.14
val isKotlinFun: Boolean = true
val letter: Char = ‘K’
val greeting: String = “Hello”
```

## 3. **Control Flow**

### Conditional Statements
```kotlin
val number = 10
if (number > 0) {
println(“Positive”)
} else if (number < 0) {
println(“Negative”)
} else {
println(“Zero”)
}
```

### When Expression
The `when` expression replaces the `switch` statement in Java.

```kotlin
val day = 3
when (day) {
1 -> println(“Monday”)
2 -> println(“Tuesday”)
3 -> println(“Wednesday”)
else -> println(“Weekend”)
}
```

### Loops
```kotlin
// For Loop
for (i in 1..5) {
println(i)
}

// While Loop
var i = 0
while (i < 5) {
println(i)
i++
}
```

## 4. **Functions**

### Basic Function
```kotlin
fun greet(name: String): String {
return “Hello, $name!”
}
```

### Function with Default Parameters
```kotlin
fun greet(name: String, greeting: String = “Hello”): String {
return “$greeting, $name!”
}
```

### Named Arguments
```kotlin
greet(name = “John”, greeting = “Hi”)
```

### Higher-Order Functions
Functions that take other functions as parameters or return functions.

```kotlin
fun operate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}

val sum = operate(3, 4) { x, y -> x + y }
```

## 5. **Classes and Objects**

### Basic Class
```kotlin
class Person(val name: String, var age: Int) {
fun introduce() {
println(“Hi, I’m $name and I’m $age years old.”)
}
}

val person = Person(“Alice”, 25)
person.introduce()
```

### Data Classes
Data classes are used for holding data.

```kotlin
data class User(val name: String, val age: Int)
```

### Inheritance
```kotlin
open class Animal(val name: String) {
open fun makeSound() {
println(“Some sound”)
}
}

class Dog(name: String) : Animal(name) {
override fun makeSound() {
println(“Woof”)
}
}

val dog = Dog(“Buddy”)
dog.makeSound()
```

## 6. **Null Safety**

### Nullable Types
```kotlin
var name: String? = “Kotlin”
name = null
```

### Safe Calls
```kotlin
val length: Int? = name?.length
```

### Elvis Operator
Provides a default value when the expression is null.

```kotlin
val length = name?.length ?: 0
```

## 7. **Collections**

### Lists
```kotlin
val list = listOf(1, 2, 3, 4)
val mutableList = mutableListOf(1, 2, 3)
mutableList.add(4)
```

### Maps
```kotlin
val map = mapOf(“one” to 1, “two” to 2)
val mutableMap = mutableMapOf(“one” to 1)
mutableMap[“two”] = 2
```

### Sets
```kotlin
val set = setOf(1, 2, 3, 3)
val mutableSet = mutableSetOf(1, 2)
mutableSet.add(3)
```

## 8. **Extension Functions**

```kotlin
fun String.lastChar(): Char = this[this.length — 1]

val str = “Kotlin”
println(str.lastChar())
```

## 9. **Coroutines**

Coroutines are used for asynchronous programming.

### Basic Example
```kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
launch {
delay(1000L)
println(“World!”)
}
println(“Hello,”)
}
```

### Suspended Functions
```kotlin
suspend fun doSomething() {
delay(1000L)
println(“Done”)
}
```

## 10. **Lambda Expressions**

```kotlin
val add: (Int, Int) -> Int = { x, y -> x + y }
println(add(2, 3))
```

## 11. **Sealed Classes**

Sealed classes are used for representing restricted class hierarchies.

```kotlin
sealed class Result
data class Success(val data: String) : Result()
data class Failure(val error: String) : Result()

fun handleResult(result: Result) {
when (result) {
is Success -> println(“Success with data: ${result.data}”)
is Failure -> println(“Failure with error: ${result.error}”)
}
}
```

## 12. **Generics**

### Generic Function
```kotlin
fun <T> printItem(item: T) {
println(item)
}
```

### Generic Class
```kotlin
class Box<T>(val value: T)

val intBox = Box(123)
val stringBox = Box(“Hello”)
```

## 13. **Type Aliases**

Type aliases provide alternative names for existing types.

```kotlin
typealias UserMap = Map<String, User>
```

## 14. **Properties and Fields**

### Custom Accessors
```kotlin
var temperature: Int = 0
get() = field
set(value) {
field = value
}
```

## 15. **Annotations**

Annotations are used to provide metadata.

```kotlin
@Target(AnnotationTarget.FUNCTION)
annotation class TestAnnotation

@TestAnnotation
fun annotatedFunction() {
// Function code
}
```

— RAHUL CHUABE

https://www.linkedin.com/in/rahulchaube1/

--

--

Rahul Chaube
Rahul Chaube

Written by Rahul Chaube

Developer | Founder/CEO @Artistic Impression | COO @IB NGO | CSE @SRM IST | Java, Python, C++ | E-learning & AeroInkT Innovator | Tech & Art Enthusiast

No responses yet