In this demo, you’ll learn how to create a custom function and call it from your code. You’ll be using Kotlin Playground to edit and run the code. To follow along, go to https://play.kotlinlang.org/, or fire up your browser and type Kotlin Playground in the search bar. The first link should take you to the Kotlin Playground.
Here, the main() function is already defined. main() is the entry point to a Kotlin program. Any code inside the curly braces will be executed.
Now, you’ll create a function that finds the square root of 289 and prints the square root to the screen:
fun findSquareRoot() {
val squareRoot = sqrt(289.00)
println("Square root is $squareRoot")
}
You declared a function using the fun keyword, followed by the function’s name: findSquareRoot. In the findSquareRoot() function, you used the predefined sqrt() function to calculate the square root of 289. Then, you called the println() function to print the result to the screen.
You’ve written the function. Now, it’s time to execute it. You’ll call the findSquareRoot() function from the main() function. You’d remove the println() function call in the main function.
fun main() {
findSquareRoot()
}
Next, run the code. Whoops! The code has a bug. To fix the bug, make sure to include the kotlin.math.sqrt package above the main function:
import kotlin.math.sqrt
fun main() {
findSquareRoot()
}
Now, run the code again. It executes successfully and prints 17, the square root of 289 on the screen.
Right now, the findSquareRoot() function doesn’t return a value. Here’s how you know.
Assign the value returned by the findSquareRoot() function to a variable called result. Then, print the value stored in the result variable:
fun main() {
val result = findSquareRoot()
println("result is $result")
}
When you run the code, the following is printed to the screen:
result is kotlin.Unit
The value stored in the result variable is Unit. If a function doesn’t return a value, its return type will always default to Unit. You’ll learn more about returning values from functions in a future lesson.
That concludes this demo. Move to the next part of the module for a quick summary.