Start learning free

LESSON 36 OF 348 · FUNCTIONS I

Function Parameters and Arguments in Kotlin

Lesson Read the full explanation

So far, the functions we've created execute a fixed task without context / inputs. But most often we want our functions to produce different outcomes depending on the context behind the function call.

For example, it would be nice if sayHello() would print a personalized message such as "Hello humans" or "Hello cats" or "Hello dogs", depending on the audience instead of "Hello world" no matter what.


Function parameters:

Function parameters allow functions to accept input(s) and perform a task using the input(s). We use parameters as placeholders for information that will be passed to the function when it is called.

When a function is defined, its parameters are specified between the parentheses that follow the function name.

Here is our function with one String parameter, audience:

fun sayHello(audience: String) {
  println("Hello $audience")
}

Calling with arguments:

Then we can call sayHello() and specify the values in the parentheses that follow the function name. The values that are passed to the function when it is called are called arguments.

// Function declaration:
fun sayHello(audience: String) {
	println("Hello $audience")
}

// Function call:
sayHello("humans") // Output: Hello humans

We have passed one string argument: "humans". Inside the function audience will equal string "humans" and acts just like a regular variable.


Multiple parameters:

A function can have as many parameters as it needs. Here is a function with two parameters:

fun sayHello(name: String, age: Int) {
  println("$name, aged $age")
}

// Let's call it:
sayHello("John", 30) // Output: John, aged 30
sayHello("Mary", 26) // Output: Mary, aged 26

Notice that the order in which arguments are passed and assigned follows the order that the parameters are declared.


Variables as arguments:

Variables can also be passed as arguments for function calls:

fun sayHello(name: String, age: Int) {
  println("$name, aged $age")
}

val name = "Andy"
val age = 28

sayHello(name, age) // Output: Andy, aged 28

sayHello("Mary", age) // Output: Mary, aged 28

Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 5
    Ctrl + Enter to check

    KOTLIN · FUNCTIONS I

    Function Parameters And Arguments in Kotlin, explained

    Why functions take input

    The functions so far did the same thing every time. A function like sayHello() can print only one fixed message. Usually you want the result to depend on the situation: a greeting for humans in one call and for cats in another. Parameters make that possible.

    Parameters and arguments

    A parameter is a placeholder for a value, declared in the parentheses of the function definition. In Kotlin, a parameter is written as its name, a colon and its type:

    fun sayHello(audience: String) {
        println("Hello $audience")
    }
    

    An argument is the actual value passed in a call. Inside the function, the parameter behaves like a variable holding that value:

    sayHello("humans")
    
    Hello humans
    

    In short, the parameter is the name in the definition, and the argument is the value in the call. Each call can pass a different argument, so one definition serves any audience.

    String templates

    The text "Hello $audience" is a string template. A dollar sign followed by a name is replaced by that variable's value. To insert a longer expression, use braces: "${name.length}" inserts the length of name. Without braces, only the name right after the $ is substituted, so with val name = "Andy", the text "$name.length" gives Andy.length and not 4.

    Several parameters

    A function can have as many parameters as it needs, separated by commas:

    fun sayHello(name: String, age: Int) {
        println("$name, aged $age")
    }
    
    fun main() {
        sayHello("John", 30)
        sayHello("Mary", 26)
    }
    
    John, aged 30
    Mary, aged 26
    

    Arguments are matched to parameters by position: the first argument goes to the first parameter, the second to the second. Swapping them is an error here, since 26 is not a String. Kotlin also lets you name the arguments in a call, which makes the order free: sayHello(age = 26, name = "Mary") prints the same line as before.

    Variables as arguments

    An argument can be any expression, including a variable. The function receives the variable's value. The variable in the caller and the parameter in the function are different names that happen to hold the same value, and they don't have to match: a caller's val name = "Andy" can be passed to a parameter called anything.

    What the compiler checks

    Parameter types are checked when the code is compiled. For a function welcomeUser(name: String):

    • calling welcomeUser() with no argument gives the error no value passed for parameter 'name'.;
    • calling welcomeUser(5) gives argument type mismatch: actual type is 'Int', but 'String' was expected.;
    • calling welcomeUser("a", "b") reports too many arguments;
    • assigning to the parameter inside the function, as in name = "x", gives 'val' cannot be reassigned., because Kotlin parameters are read-only.

    The lesson's exercise, step by step

    The starter code is a class named Solution with an empty mainFunction. All the code goes inside the class.

    1. Define welcomeUser with one String parameter called name, above mainFunction.
    2. Print a greeting with a string template. The body is println("Welcome, $name!"), so for "Andy" it prints Welcome, Andy!. The exclamation mark right after $name doesn't belong to the name, because a name can't contain it.
    3. Call welcomeUser("Andy") inside mainFunction. The string argument becomes the value of name for that call.
    4. Create val name = "John" in mainFunction. It is a val, since the value is never reassigned.
    5. Call welcomeUser(name). The variable's value, "John", is the argument.
    class Solution {
        fun welcomeUser(name: String) {
            println("Welcome, $name!")
        }
    
        fun mainFunction() {
            welcomeUser("Andy")
            val name = "John"
            welcomeUser(name)
        }
    }
    

    Calling mainFunction() on a Solution object prints:

    Welcome, Andy!
    Welcome, John!
    

    Here the functions are written inside a class, which makes them member functions. They can call each other by name, as mainFunction calls welcomeUser. Outside the class, you would call them on an object, as in Solution().mainFunction().

    Common mistakes

    • Omitting the type. fun welcomeUser(name) is not valid, because every Kotlin parameter needs a type.
    • Writing the type first. String name is the order of other languages. Kotlin uses name: String.
    • Forgetting the dollar sign. "Welcome, name!" prints the word name and not the value.
    • Passing arguments in the wrong order. With several parameters of the same type, a swap compiles and prints wrong output.

    Key takeaways

    • Parameters are declared in the definition as name: Type. Arguments are the values given in the call.
    • Arguments are matched by position, or by name when you write the name in the call.
    • Parameters are read-only inside the function.
    • $name puts a variable into a string, and ${...} puts in an expression.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free