Middle
What does the 'suspend' keyword mean in Kotlin?
sobes.tech AI
Answer from AI
The suspend keyword in Kotlin is used to mark a function or lambda expression as potentially pausable and resumable later. Such functions are called coroutines.
Main properties of suspend functions:
- They can only be called from another
suspendfunction or within a coroutine scope. - Suspending a function does not block the thread in which it runs. Instead, the thread can be used to perform other tasks.
- After completing a suspended operation (e.g., a network request), the function resumes from where it was suspended.
- Behind the scenes, the Kotlin compiler transforms
suspendfunctions into state machines using Continuation-Passing Style (CPS).
Example:
// Example suspend function to simulate a long operation
suspend fun fetchData(): String {
// Simulate a network request or a long task
kotlinx.coroutines.delay(1000) // Suspension without blocking the thread
return "Data received"
}
// Function calling a suspend function
fun main() = kotlinx.coroutines.runBlocking { // runBlocking creates a coroutine scope
println("Loading data...")
val data = fetchData() // Call to suspend function
println("Data: $data")
}