Defining functions
- Kotlin course
- Beginner
- Lesson 71/116
- 4 min
Learn to define functions with fun.
Defining functions: fun
In Kotlin a function starts with the fun keyword. Parameters are written as name: Type; the body sits inside { }. To call it, write the function name and the arguments in parentheses.
fun greet(name: String) {
println("Hello $name")
}
greet("Ava") // Hello AvaParameters are separated by commas: fun add(a: Int, b: Int). Type names start with a capital: Int, String, Boolean.
Function call and argument order
To call a defined function, write its name and the arguments in parentheses. Arguments bind to parameters by position: the first argument goes to the first parameter, the second to the second.
fun greet(name: String, msg: String) {
println("$msg $name")
}
greet("Ava", "Hi") // Hi AvaThe argument count must match the parameter count; otherwise you get a compile error. This makes the call checked at compile time.
Practice Define greet and call it
Define a fun greet(name: String) whose body is println("Hello $name"). From main call greet("Ava").
Starter code
fun main() {
// Call greet with "Ava"
}
// Define greet with a String parameter
// In the body, print a greeting using $nameSample solution
fun main() {
greet("Ava")
}
fun greet(name: String) {
println("Hello $name")
}Expected output
Hello Ava
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: parameter type
fun greet(name: ____) {
println(name)
}
fun greet(name: String) {
println(name)
}
Explanation: name: String takes a text argument.
2 Which is a valid Kotlin function definition?
- function greet(name: String) { println(name) }
- fun greet(name: String) { println(name) } Correct answer
- def greet(name: String) { println(name) }
- greet(name: String) -> { println(name) }
Explanation: Kotlin functions start with fun; parameters use the name: Type form.
3 Match function part to role
| Term | Meaning |
|---|---|
fun |
Starts the function definition |
name: String |
String-typed parameter |
{ } |
Function body |
greet("Ava") |
Function call |