In: Computer Science
import kotlinx.coroutines.*
// TODO 1
fun sum(valueA: Int, valueB: Int): Int {
return 0
}
// TODO 2
fun multiple(valueA: Int, valueB: Int): Int {
return 0
}
fun main() = runBlocking {
println("Counting...")
val resultSum = async { sum(10, 10)
}
val resultMultiple = async { multiple(20, 20)
}
// TODO 3
println()
}
TODO 1:
Change it to suspend function with the following conditions:
Has a waiting time of 3 seconds before the next operation
runs.
Returns the value of the sum of valueA and valueB.
TODO 2:
Change it to suspend function with the following conditions:
Has a waiting time of 2 seconds before the next operation
runs.
Returns the value of the multiplication valueA and valueB.
TODO 3:
Add a function to print the deferred values of the resultSum and
resultMultiple variables on the console.
If run, the console will display the text:
Counting ...
Result sum: 20
Multiple results: 400
Below is the solution:
import kotlinx.coroutines.*
// TODO 1
fun sum(valueA: Int, valueB: Int): Int {
Thread.sleep(3_000) //wait 3 second
val sum = valueA + valueB
return sum
}
// TODO 2
fun multiple(valueA: Int, valueB: Int): Int {
Thread.sleep(2_000) //wait 2 second
val mul = valueA * valueB
return mul
}
fun main() = runBlocking {
println("Counting...")
val resultSum = async { sum(10, 10) }
val resultMultiple = async { multiple(20, 20)
}
// TODO 3
print("Result sum: ${resultSum.await()}")
//print the result of sum
println()
print("Multiple results:
${resultMultiple.await()}") //print the result of
multiply
}
sample output:
Counting...
Result sum: 20
Multiple results: 400