Kotlin Parameters and Arguments Tutorial 🎯

beginner
8 min

Kotlin Parameters and Arguments Tutorial 🎯

Welcome to our comprehensive guide on Kotlin Parameters and Arguments! In this lesson, we'll explore how to pass data into functions, methods, and constructors in Kotlin.

What are Parameters and Arguments? 📝

In programming, parameters are the variables that are defined inside a function or method's parentheses. They represent the input data that the function will work with. On the other hand, arguments are the actual values that you provide when calling a function or method.

Defining Parameters 💡

Let's start by defining a simple function with a parameter:

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

In this example, name is our parameter. It's of type String, which means it can hold text values.

Calling a Function with Arguments ✅

Now, let's call our greet function and pass an argument:

kotlin
greet("Alice")

When you run this code, Kotlin will replace $name with "Alice", and the output will be Hello, Alice!.

Function Parameters Types 💡

Kotlin supports various types of parameters, including:

  • Value Parameters: These are the regular parameters we've seen. Their values are copied into the function and any changes made to them inside the function do not affect the original values.

  • Variable Parameters: These parameters can be called multiple times with different values. They are stored in a mutable list.

  • Named Parameters: Instead of passing parameters in the order they are defined, you can pass them with their names. This is useful when parameters have similar names or when you want to pass parameters in any order.

We'll explore these types in more detail in future lessons.

Default Parameter Values 💡

You can also assign default values to parameters. If no argument is provided when calling the function, the default value will be used.

kotlin
fun greet(name: String = "Guest") { println("Hello, $name!") } greet() // Output: Hello, Guest!

Functions with Multiple Parameters 💡

Functions can have multiple parameters. Just separate them with commas.

kotlin
fun greet(name: String, age: Int) { println("Hello, $name! You are $age years old.") } greet("Alice", 30) // Output: Hello, Alice! You are 30 years old.

Constructor Parameters 💡

Constructors in Kotlin work similar to functions, but they are used to create objects. Here's an example:

kotlin
class Person(name: String, age: Int) { var myName: String = name var myAge: Int = age } val alice = Person("Alice", 30)

In this example, name and age are constructor parameters. When creating a new Person object, you must provide values for these parameters.

Quiz 💡

Quick Quiz
Question 1 of 1

What is the purpose of parameters in a function?

That's it for this lesson! We've covered the basics of parameters and arguments in Kotlin. In the next lesson, we'll dive deeper into more advanced topics. Until then, happy coding! 🚀