96. The concept of crossinline in Kotlin.
In Kotlin, crossinline is used with inline functions to prevent a lambda from using non-local returns.
By default, lambdas passed to an inline function can use non-local returns — meaning the lambda can return from the outer function.
But in some cases (like when the lambda is called inside another function, thread, or coroutine), that behavior is not allowed. You must use crossinline to disable non-local returns and ensure safe behavior.
Basic Example Without crossinline
inline fun myFunction(action: () -> Unit) {
println("Before action")
action() // This can use return@myFunction or return (non-local)
println("After action")
}
This is fine:
myFunction {
println("Inside lambda")
return // Non-local return: exits outer function too!
}
If you do this:
inline fun doSomething(action: () -> Unit) {
Thread {
action() // Error if lambda tries to use `return`
}.start()
}
Trying to use return inside action() here will cause a compilation error, because the lambda is being executed inside another thread, not inlined directly.
Solution: Use crossinline
inline fun doSomething(crossinline action: () -> Unit) {
Thread {
action() // Now lambda can't use non-local return
}.start()
}
Now this works:
doSomething {
println("Hello from another thread!")
// return ❌ NOT allowed here (will show compile error)
}
Important Table :
Modifier | Meaning |
---|---|
inline | Copies the function code with the lambda |
noinline | Lambda is not inlined |
crossinline | Lambda is inlined but non-local return is not allowed |
97. What is the requireNotNull function in Kotlin?
requireNotNull() is a standard Kotlin function used to ensure a nullable value is not null at runtime. If the value is null, it throws an IllegalArgumentException.
Function Signature
fun <T : Any> requireNotNull(value: T?): T
It can also take a custom message:
fun <T : Any> requireNotNull(value: T?, lazyMessage: () -> Any): T
Example
fun printLength(str: String?) {
val nonNullStr = requireNotNull(str) { "String must not be null" }
println("Length: ${nonNullStr.length}")
}
Use it when:
Related Functions
Function | Throws | When |
---|---|---|
require(condition) | IllegalArgumentException | If condition is false |
check(condition) | IllegalStateException | If internal state is invalid |
requireNotNull(value) | IllegalArgumentException | If value is null |
checkNotNull(value) | IllegalStateException | If value is null |
98. What is the checkNotNull function in Kotlin?
checkNotNull() is a standard Kotlin function that checks whether a value is null, and throws an exception if it is.
Syntax
fun <T : Any> checkNotNull(value: T?, message: () -> Any): T
Example
val name: String? = null
val result = checkNotNull(name) { "Name must not be null!" }
// Throws: IllegalStateException: Name must not be null!
Use checkNotNull() when:
Safe Version
val name: String? = getNameOrNull()
val finalName: String = checkNotNull(name) { "Unexpected null name" }
It will:
99. What are these require & check functions in Kotlin?
In Kotlin, require() and check() are two standard functions used for validating conditions at runtime. They help you fail fast and catch bugs early.
Example:
fun setAge(age: Int) {
require(age >= 0) { "Age must be non-negative" }
println("Age set to $age")
}
Output:
setAge(-5) // Throws: IllegalArgumentException: Age must be non-negative
fun startEngine(engineStarted: Boolean) {
check(engineStarted) { "Engine must be started first" }
println("Engine is running")
}
100. Differences among requireNotNull, checkNotNull, require & check function in Kotlin?
In Kotlin, require, check, requireNotNull, and checkNotNull are standard functions used to enforce preconditions and invariants at runtime. They help in writing defensive code by throwing meaningful exceptions when conditions are not met.
Function | Purpose | Used for | Exception Thrown |
---|---|---|---|
require(...) | Validate arguments | Function parameters | IllegalArgumentException |
check(...) | Validate internal state | Object invariants | IllegalStateException |
requireNotNull(...) | Ensure a value is not null | Arguments (nullable check) | IllegalArgumentException |
checkNotNull(...) | Ensure a value is not null | Internal state (nullable) | IllegalStateException |