Menu
Coddy logo textTech

Parameters And Arguments

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 56 of 93.

Functions become much more powerful when they can accept input. Parameters are variables defined in the function declaration that act as placeholders for values the function will receive.

fun greet(name: String) {
    println("Hello, $name!")
}

fun main() {
    greet("Alice")
    greet("Bob")
}
// Output:
// Hello, Alice!
// Hello, Bob!

Here, name is a parameter - it's defined inside the parentheses with its type. When we call the function, we pass an argument - the actual value like "Alice" or "Bob". The parameter receives this value and uses it inside the function.

Functions can have multiple parameters, separated by commas:

fun introduce(name: String, age: Int) {
    println("$name is $age years old")
}

fun main() {
    introduce("Emma", 25)
}
// Output: Emma is 25 years old

When calling a function with multiple parameters, the arguments must be provided in the same order as the parameters are defined. Each parameter needs its type specified, even if they're the same type.

challenge icon

Challenge

Medium

Create a function called describePet that takes two parameters: name (String) and age (Int).

The function should print the following message:

[name] is [age] years old.

In your main function, read two inputs: a pet name (String) and an age (Int). Then call describePet with these values.

For example, if the inputs are:

Buddy
3

The output should be:

Buddy is 3 years old.

Try it yourself

fun main() {
    // Read input
    val name = readLine()!!
    val age = readLine()!!.toInt()
    
    // TODO: Create the describePet function and call it with name and age
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground