91. The use of the with function in Kotlin
The with function in Kotlin is a scope function used to execute multiple operations on a single object without repeatedly referencing the object.
Syntax
with(receiverObject) {
// Access properties and methods of receiverObject directly
}
- receiverObject is the object you're operating on
Example
val user = User("Alice", 25)
with(user) {
println(name)
println(age)
}
This is equivalent to:
println(user.name)
println(user.age)
But with makes it cleaner for multiple operations.
When to Use with
Situation | Use with if… |
---|---|
Multiple operations on one object | ✅ Yes |
No need to return the object | ✅ Yes |
Want to return a result from block | ✅ Yes |
Need to use this inside block | ✅ Yes |
92. Compare with apply and run
Feature | apply | run |
---|---|---|
Return value | Returns the receiver object | Returns the last expression value |
Receiver (this) | Yes (this) | Yes (this) |
Usage Purpose | Configure or initialize an object | Execute a block and return a result |
Typical Use Case | Builder-style object setup | Execute code and get a computed result |
Object context | Implicit this | Implicit this |
Receiver required | Always called on an object | Can be called on an object or as a lambda block |
Mutates object? | Often mutates | Often pure, or returns different result |
Null-safe version | Not nullable | someObject?.run { ... } ✅ |
Example: apply
val person = Person().apply {
name = "Alice"
age = 30
}
Returns the person object itself (after configuration)
Example: run
val greeting = person.run {
"Hello, my name is $name and I am $age years old."
}
Returns the result of the last line, i.e., the String
93. The concept of the internal visibility modifier in Kotlin
The internal visibility modifier in Kotlin means:
The member is visible everywhere within the same module, but not outside the module.
Modifier | Visibility Scope |
---|---|
public | Everywhere (default if not specified) |
internal | Same module only |
protected | Subclasses only (and only within the class scope) |
private | Only within the same class/file |
Use internal when:
- You want to hide implementation details within a module
- You're building a library or shared KMP module
- You want to prevent other modules from accessing certain classes/functions
In KMP, internal means the code is visible:
- Across all source sets in the same shared module
- But not to consuming platforms (e.g., Android/iOS) unless they’re in the same module
94. What is a "Module"?
- In Android: a module is usually an Android Studio module (like :app or :core)
- In Kotlin Multiplatform (KMP): a module can be a shared KMP source set
- In Gradle: it's typically one build.gradle.kts (or build.gradle) unit
In programming, a module is a self-contained, reusable unit of code that encapsulates related functionality. It helps organize, isolate, and manage code in large projects.
A module typically includes:
- Code (functions, classes, variables)
- Resources (files, images, etc.)
- Dependencies (libraries it uses)
Think of it as a "sub-project" or "package" inside a larger project.
In Android or Kotlin projects:
-A module is a Gradle subproject (app, feature-login, core-utils, etc.)
- Can be:
- Application module – e.g., your main app
- Library module – reusable code used by other modules
Benefits:
- Modular architecture
- Faster builds
- Better reusability
- Code separation (e.g., domain layer, data layer)
// settings.gradle.kts
include(":app", ":login", ":network")
Why Use Modules?
Benefit | Description |
---|---|
Reusability | Write once, use across multiple projects |
Maintainability | Smaller, focused code units |
Encapsulation | Hide internal logic |
Team Collaboration | Teams can work on separate modules |
Build Optimization | Only rebuild affected modules |
95. The difference between first() and firstOrNull() functions in Kotlin
Both first() and firstOrNull() are used to retrieve the first element of a collection or sequence in Kotlin — but they behave differently when the collection is empty or no match is found.
- Returns the first element of a collection or matching predicate.
- ❗️ Throws an exception if:
- The collection is empty.
- No element matches the given condition.
val list = listOf<Int>()
val result = list.first() // ❌ Throws NoSuchElementException
With a predicate:
val list = listOf(1, 2, 3)
val result = list.first { it > 5 } // ❌ Throws NoSuchElementException
- Returns the first element if present.
- ✅ Returns null instead of throwing an exception when:
- The collection is empty.
- No element matches the predicate.
val list = listOf<Int>()
val result = list.firstOrNull() // ✅ Returns null
With a predicate:
val list = listOf(1, 2, 3)
val result = list.firstOrNull { it > 5 } // ✅ Returns null
- You're sure the list isn't empty and will have a matching element.
- The list may be empty or the element might not match a condition, and you want to avoid exceptions.
Feature | first() | firstOrNull() |
---|---|---|
Returns | The first matching element | The first matching element or null |
Throws Exception? | ✅ Yes – NoSuchElementException if no match | ❌ No – Returns null if no match |
Nullable Return Type | ❌ No – Returns non-nullable type | ✅ Yes – Returns nullable type (T?) |
Use Case | When you're sure at least one element matches | When list might be empty or no match |
Usage with Condition | list.first { it > 10 } | list.firstOrNull { it > 10 } |
Usage without Condition | list.first() | list.firstOrNull() |