Kotlin Interview Preparation Tutorial: Key Topics, val vs var, lateinit vs lazy, Coroutines, Scope Functions, Data Classes, and Sealed Classes
This Kotlin Interview Preparation tutorial covers essential interview topics including val vs var, lateinit vs lazy, coroutines vs threads, data class usage, scope function differences, and sealed classes vs enums. The chapter provides concise examples, best practices, and insights to help developers prepare for Kotlin interviews and advance their careers.
Kotlin Interview Topics (Complete Guide)
val vs var
val: Immutable reference (cannot be reassigned).var: Mutable reference (can be reassigned).
Example
Best Practice
- Prefer
valunless mutability is required - Improves thread safety and readability
lateinit vs lazy
lateinit
- Used for variables initialized later
- Must be non-nullable
- Only works with
var
lazy
- Initialized on first access
- Works with
val - Thread-safe by default
Best Practice
- Use
lazyfor expensive initialization - Use
lateinitfor dependency injection or Android Views
Coroutines vs Threads
| FeatureThreadsCoroutines | ||
| Lightweight | Heavy | Very lightweight |
| Creation cost | Expensive | Cheap |
| Blocking | Yes | No (suspend functions) |
| Use case | Low concurrency tasks | High concurrency, I/O tasks |
Example Coroutine
Best Practice
- Prefer coroutines for async tasks
- Avoid blocking main thread in Android
- Use structured concurrency (
CoroutineScope)
Data Class Usage
- Automatically provides
equals(),hashCode(),toString(), andcopy(). - Ideal for immutable data holders.
Example
Best Practice
- Use for DTOs, API responses, and immutable objects
Scope Function Differences
Kotlin has five scope functions: let, run, with, apply, also.
| FunctionContext ObjectReturnUse Case | |||
let | it | Lambda result | Null-safety, chaining |
run | this | Lambda result | Object configuration |
with | this | Lambda result | Object configuration, no extension |
apply | this | Object | Object initialization |
also | it | Object | Side-effects, logging |
Example
Best Practice
- Choose scope function based on
this/itand return requirement - Use
applyfor builder-style initialization
Sealed Class vs Enum
Enum
- Represents fixed set of constants
- Simple use cases
Sealed Class
- Represents restricted class hierarchy
- Can contain state and data
- Useful for complex state management
Best Practice
- Use enums for fixed constants
- Use sealed classes for result/state modeling
Summary
This chapter covered essential Kotlin interview topics: val vs var, lateinit vs lazy, coroutines vs threads, data class usage, scope function differences, and sealed classes vs enums. Understanding these topics, along with practical examples, prepares developers for Kotlin interviews and career growth.