7. Type inference in Kotlin.
Type inference in Kotlin means that the compiler can automatically detect the type of a variable or expression without you explicitly specifying it.
- Reduces boilerplate code.
- Makes code cleaner and more concise.
- Still keeps the benefits of strong typing (type safety).
Example 1: Variable Declaration
val name = "Bind the Logic" // Inferred as String
val age = 25 // Inferred as Int
val isActive = true // Inferred as Boolean
You don't need to write:
val name: String = "Bind the Logic"
Example 2: Function Return Type
fun getGreeting() = "Welcome to Kotlin!" // Inferred as String
But in complex functions, you might still need to specify the return type:
fun calculate(): Int {
return 5 * 10
}
Example 3: Collections
val numbers = listOf(1, 2, 3) // Inferred as List<Int>
val names = mapOf("A" to "Apple", "B" to "Banana") // Map<String, String>
When You Should Specify Type
- When the initialization is missing:
var result // ❌ Error: Type can't be inferred
- Or the type is ambiguous:
val nothing = null // Inferred as Nothing? (needs explicit type)
8. What are Kotlin Collections?
Collections in Kotlin are data containers that hold multiple values in a single variable. Kotlin offers a rich set of built-in collection types that make handling groups of data simple and expressive.
Type | Description | Example |
List | Ordered collection (can have duplicates) | listOf("A", "B", "C") |
Set | Unordered collection with unique items | setOf("A", "B", "C") |
Map | Collection of key-value pairs | mapOf("a" to 1, "b" to 2) |
1. List
immutable List (Read-only)
val fruits = listOf("Apple", "Banana", "Cherry")
println(fruits[0]) // Apple
Mutable List (Can change)
val fruits = mutableListOf("Apple", "Banana")
fruits.add("Orange")
2. Set
Immutable Set
val colors = setOf("Red", "Green", "Blue")
Mutable Set
val colors = mutableSetOf("Red", "Green")
colors.add("Blue") // Adds only if not already present
3. Map
Immutable Map
val capitals = mapOf("India" to "Delhi", "USA" to "Washington")
println(capitals["India"]) // Delhi
Mutable Map
val capitals = mutableMapOf("India" to "Delhi")
capitals["UK"] = "London"
Common Operations
val list = listOf(1, 2, 3, 4)
// forEach
list.forEach { println(it) }
// map
val doubled = list.map { it * 2 } // [2, 4, 6, 8]
// filter
val even = list.filter { it % 2 == 0 } // [2, 4]
// find
val firstEven = list.find { it % 2 == 0 } // 2
9 . Difference Between List and Array in Kotlin
Feature | List | Array |
---|---|---|
Definition | An interface representing an ordered collection. | A class that represents a fixed-size collection. |
Mutability | Use List (immutable) or MutableList (mutable). | Arrays are mutable by default. |
Size | Can be dynamically changed with MutableList. | Fixed size once created. |
Type Safety | Can use generics: List<String>, List<Int> etc. | Stores elements of the same data type. |
Syntax | val list = listOf(1, 2, 3) | val array = arrayOf(1, 2, 3) |
Access | list[0], list.get(0) | array[0], array.get(0) |
Performance | Slightly more overhead due to abstraction. | Generally faster and uses less memory. |
Usage | Preferred for collection-based operations. | Preferred for performance-critical or fixed-size data. |
Example: List
val list = listOf("Kotlin", "Java", "Swift") // Immutable
val mutableList = mutableListOf(1, 2, 3)
mutableList.add(4)
Example: Array
val array = arrayOf(1, 2, 3)
array[0] = 10 // Can change values
- Use List if you want:
- More flexibility
- Built-in collection operations (map, filter, etc.)
- Functional programming support
Use Array if you want:
- Fixed-size data
- Better performance (in tight loops, etc.)
10. What is a lambda expression in Kotlin?
A lambda expression in Kotlin is a concise way to define an anonymous function (a function without a name). It's often used to pass behavior as a parameter to functions.
Syntax of Lambda Expression:
val lambdaName: Type = { parameterList -> body }
Or more commonly:
val greet = { name: String -> println("Hello, $name!") }
greet("Alice") // Output: Hello, Alice!
{} – curly braces enclose the lambda.
name: String – parameter with its type.
-> – separates parameters from the function body.
println("Hello, $name!") – the lambda body (function logic).
Example 1: Simple Lambda
val sum = { a: Int, b: Int -> a + b }
println(sum(3, 4)) // Output: 7
Example 2: Lambda as Function Parameter
fun operate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
val result = operate(5, 3) { x, y -> x * y }
println(result) // Output: 15
- To write cleaner, shorter code.
- To treat functions as variables (functional programming).
- To pass behavior as arguments (e.g., in collection functions like map, filter, etc.)
Real-life Example: Using filter
val numbers = listOf(1, 2, 3, 4, 5)
val evens = numbers.filter { it % 2 == 0 }
println(evens) // Output: [2, 4]
Here, { it % 2 == 0 } is a lambda expression.