Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3
To pass a code block as argument in Kotlin functions, you need to use lambdas. For example, the forEach{} function can be defined as follows: forEach(action: (Int) -> Unit) Here, action is the name of the argument, "(Int)" define the type of argument to be passed like Int, String, etc. It can even be empty. And finally the Unit is the return type of the code block.
23rd Dec 2022, 7:24 PM
Rivan
+ 1
Unit means that the code block will return nothing, similar to "void" in Java. Since in this case the code block is an argument therefore it should not return anything.
24th Dec 2022, 4:28 AM
Rivan
+ 1
You're welcome!
24th Dec 2022, 10:05 AM
Rivan
+ 1
belal bayrakdar In the initial answer, I had written that you shouldn't change the return type of the function, however, I was wrong and you can set it to any return type.
8th Jan 2023, 2:44 PM
Rivan