suspend
- Kotlin course
- Intermediate
- Lesson 84/116
- 5 min
Learn suspendable functions with suspend fun.
suspend functions
A suspend function can suspend and resume its work. The definition suspend fun compute(): Int { delay(100); return 42 } computes a value but releases the thread while waiting.
Suspend functions can be called only from a coroutine or another suspend function. Calling them from a regular function is a compile error. This constraint ensures waiting always happens in a coroutine context. They can be called safely from runBlocking or launch.
The suspend keyword
The suspend keyword goes at the start of a function declaration. Example: suspend fun compute(): Int. The body can call other suspend functions like delay.
The return value of a suspend function is used like a normal function. runBlocking { println(compute()) } waits for compute to finish and prints the result. Waiting does not block the thread; during delay other work can proceed. This lets concurrent code look synchronous.
Practice Define and call a suspend function
Add import kotlinx.coroutines.*. Define suspend fun compute(): Int { delay(100); return 42 }. Write fun main() = runBlocking { println(compute()) }.
Starter code
import kotlinx.coroutines.*
// Define the compute suspend function: returns 42 after delay
// Call compute in runBlocking in main and printSample solution
import kotlinx.coroutines.*
suspend fun compute(): Int {
delay(100)
return 42
}
fun main() = runBlocking {
println(compute())
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the suspend concepts
| Term | Meaning |
|---|---|
suspend fun |
Can pause |
delay(100) |
Wait |
return 42 |
Value |
runBlocking |
Bridge |
2 Where can a suspend function be called?
- From anywhere
- Only from main
- From a coroutine or suspend function Correct answer
- Only from a class
Explanation: A suspend function is called from a coroutine or suspend context.
3 Complete the compute body
suspend fun compute(): Int {
delay(100)
return ____
}
suspend fun compute(): Int {
delay(100)
return 42
}
Explanation: answer: 42. compute returns 42 after delay.