Instruction
Function Parameters
You can pass information to functions. This information is referred to as function parameters. For example:
fun greetings(characterName: String) {
println("Hello $characterName!")
}
The function greetings() takes only one parameter: characterName. Parameters are added inside the parentheses, starting with the parameter’s name and then the type:
Then, when you call the greetings() function, you can pass different arguments for the characterName parameter:
fun main() {
greetings("Bilbo Baggins")
greetings("Frodo Baggins")
}
This code prints the following to the screen:
Hello Bilbo Baggins!
Hello Frodo Baggins!
You can also pass more than one parameter to a function.
fun greetings(characterName: String, personType: String) {
println("Hello! I am $characterName! I'm a $personType")
}
When passing more than one parameter to a function, you use a comma to separate them.
fun main() {
greetings("Bilbo Baggins", "Hobbit")
greetings("Gandalf", "Wizard")
}
This produces the following result:
Hello! I am Bilbo Baggins! I'm a Hobbit
Hello! I am Gandalf! I'm a Wizard
Variable Number of Arguments
Imagine you want to print all the character names from your favorite novel but don’t know how many characters there are. Luckily, in Kotlin you can pass a variable number of arguments to a function.
To create a function that accepts a variable number of arguments, you mark a parameter — typically the last one — with the varag modifier:
fun printCharacterNames(novelTitle: String, vararg characterNames: String){
println("Novel => $novelTitle")
for (name in characterNames) {
print("$name\t")
}
}
Then, you call the function and pass the arguments, separating them with commas:
fun main() {
printCharacterNames(
"The Lord Of The Rings",
"Bilbo", "Frodo", "Merry", "Pippin", "Gandalf"
)
}
“The Lord Of The Rings” is the argument passed for the novelTitle parameter, and “Bilbo”, “Frodo”, “Merry”, “Pippin”, and “Gandalf” are the values passed for the argument characterNames.
That gives you this result:
Novel => The Lord Of The Rings
Bilbo Frodo Merry Pippin Gandalf
Returning Values
You’ve seen how to pass information as parameters to functions. A function can output values as well.
To return a value from a function, you specify the return type after the parentheses and use the return keyword.
For example, this function:
fun frodosHeight(): Int {
return 4
}
returns frodos height (four feet) whenevers its called.
You’ve seen the syntax to pass arguments to a function and return a value from a function. Next, you’ll walk through a hands-on demonstration to illustrate passing arguments, the difference between named and default arguments to a function, returning values, and their practical use.