Instruction

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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!")
}

fun main() {
  greetings("Bilbo Baggins")
  greetings("Frodo Baggins")
}
Hello Bilbo Baggins!
Hello Frodo Baggins!
fun greetings(characterName: String, personType: String) {
  println("Hello! I am $characterName! I'm a $personType")
}
fun main() {
 greetings("Bilbo Baggins", "Hobbit")
 greetings("Gandalf", "Wizard")
}
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.

fun printCharacterNames(novelTitle: String, vararg characterNames: String){
  println("Novel => $novelTitle")
  for (name in characterNames) {
     print("$name\t")
  }
}
fun main() {
  printCharacterNames(
      "The Lord Of The Rings",
      "Bilbo", "Frodo", "Merry", "Pippin", "Gandalf"
  )
}
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.

fun frodosHeight(): Int {
  return 4
}
See forum comments
Download course materials from Github
Previous: Introduction Next: Demo