Lesson 2
Exploring Function Parameters in Kotlin
Introduction to Function Parameters

Hello, budding developer! Today, we're exploring function parameters in Kotlin. Function parameters are the inputs given to functions. For instance, in println("Hello, world!"), "Hello, world!" is a parameter you are passing to the println() function. Parameters help functions adapt to specific pieces of information, making them incredibly versatile.

Writing a Function with a Single Parameter

We'll start by writing a function that takes a single parameter. This simple function will greet a user:

Kotlin
1// Function accepting a name and printing a greeting 2fun greetUser(name: String) { 3 println("Hello, $name!") 4} 5 6// Call the function with the name "Anne" 7greetUser("Anne") // Prints "Hello, Anne!"

In this case, name is a parameter of the type String that our greetUser function uses.

Writing a Function with Multiple Parameters

We can also create a function with multiple parameters. For example, a function could calculate a rectangle's area by accepting its length and width as parameters.

Kotlin
1// Function accepting the length and breadth of a rectangle and printing its area 2fun rectangleArea(length: Int, breadth: Int) { 3 val area = length * breadth 4 println("The area of the rectangle is $area square units.") 5} 6 7// Calculate area for a rectangle with length 5 and breadth 7 8rectangleArea(5, 7) // Prints "The area of the rectangle is 35 square units."

In this code, length and breadth are Int parameters.

Function Parameter Types

Kotlin supports different data types for parameters. For example, Int, Double, Boolean, String, Array etc. We've worked with String and Int type function parameters in the examples above.

Handling Different Numbers of Parameters

A Kotlin function can take any number of parameters -- even zero. Here's an example:

Kotlin
1// Function taking three Int parameters and printing their sum 2fun printSum(a: Int, b: Int, c: Int){ 3 println("The sum is ${a + b + c}") 4} 5 6// Call the function with 1, 2, and 3 as parameters 7printSum(1, 2, 3) // Prints "The sum is 6"
Practice Makes Perfect

True understanding of theory is best achieved through practice. So, try writing functions that take different numbers and types of parameters. For instance, you could write a function that averages three numbers.

Lesson Summary

Congrats! You've explored the world of function parameters in Kotlin, delving into their definitions, uses, and types. It's now time to put these concepts into practice by defining and using function parameters. Our next lesson will cover Function Returns. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.