Now that we understand important programming concepts like control flow, collections, and loops, we can learn how to use functions to make our programs more efficient. A function is a reusable block of code that we can call throughout our program to complete a certain task.
You may recognize the term “functions” since we’ve already implemented some in this course. The
println() function which we’ve used to output values as well as the
main() function in which all of our code has been written so far are both Kotlin standard library defined functions. In this lesson, we’ll venture outside of the
main() function and write our own user-designed functions.
User-designed functions are functions we, the developers, create in our programs in order to accomplish a specific task. There are many ways to create and use functions making them an extremely versatile tool.
In this lesson, we’ll focus our efforts on how to write and invoke user-designed functions.
Take a look at the image to the right. After spending a lot of time camping, the task of starting a campfire each night has become cumbersome for Codey. Luckily, Function Forest is known to be the habitat of a very smart bird that can remember a set of tasks and repeat them anytime they are called.
Codey teaches one of these birds all the steps needed to make a campfire: finding rocks to contain the fire, collecting kindling, and starting a flame. Now whenever Codey wants to start a campfire, they simply call upon the bird.