Kotlin Functions
A function is a named block of code that a program can call. One definition can do the same job in many places.
The same lines written twice
Two greetings need the same two lines copied here. A change would need the same edit in both places.
fun main() {
println("Hello, Ana")
println("Welcome to the course")
println("Hello, Ana")
println("Welcome to the course")
}One definition and two calls
The fun keyword defines sayHello one time. Each call runs the same two lines again.
fun sayHello() {
println("Hello, Ana")
println("Welcome to the course")
}
fun main() {
sayHello()
sayHello()
}A function with one parameter
A parameter is a named value the function receives at a call. greet takes a name and prints a greeting for that name.
fun greet(name: String) {
println("Hello, $name")
}
fun main() {
greet("Ana")
greet("Bo")
}A function with two parameters
Two parameters sit inside the parentheses with a comma between them. Each call passes two values in that order.
fun showScore(name: String, score: Int) {
println("$name scored $score")
}
fun main() {
showScore("Ana", 90)
showScore("Bo", 75)
}Example
fun greet(name: String) {
println("Hello, $name")
}
fun printStars() {
println("***")
}
fun main() {
greet("Ana")
printStars()
greet("Bo")
printStars()
}Key points
- fun: the keyword that starts a function definition.
- A call runs a function by writing its name and parentheses.
- A parameter is a named value passed into a function.
- Each call passes real values in the order the parameters are written.
- A function body is the block between its braces.
In this example, greet takes a name and prints a greeting for it. printStars takes no value and prints three stars. The main function calls greet and printStars two times each. Each call runs the lines inside its own function.
Note
A function definition does nothing until a call runs it.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
Which line defines a function named greet that takes one name?