0
0
Kotlinprogramming~30 mins

This vs it receiver difference in Kotlin - Hands-On Comparison

Choose your learning style9 modes available
This vs it Receiver Difference in Kotlin
📖 Scenario: Imagine you are organizing a small party and you want to keep track of guests and their favorite drinks. You will use Kotlin's scope functions to handle this data easily.
🎯 Goal: You will learn the difference between this and it receivers in Kotlin by using apply and let functions to manage guest information.
📋 What You'll Learn
Create a data class called Guest with properties name and favoriteDrink
Create an instance of Guest with specific values
Use apply to update the guest's favorite drink using this receiver
Use let to print a message using it receiver
💡 Why This Matters
🌍 Real World
Using <code>this</code> and <code>it</code> receivers helps Kotlin developers write clean and concise code when working with objects, especially in configuration and data manipulation tasks.
💼 Career
Understanding scope functions and their receivers is important for Kotlin developers working on Android apps or backend services, as it improves code readability and reduces errors.
Progress0 / 4 steps
1
Create the Guest data class and an instance
Create a data class called Guest with properties name of type String and favoriteDrink of type String. Then create a variable called guest and assign it an instance of Guest with name set to "Alice" and favoriteDrink set to "Water".
Kotlin
Need a hint?

Use data class Guest(var name: String, var favoriteDrink: String) to define the class.

Create guest with Guest("Alice", "Water").

2
Use apply with this receiver to update favoriteDrink
Use the apply function on the guest variable to change the favoriteDrink property to "Lemonade". Inside apply, use this.favoriteDrink to set the new value.
Kotlin
Need a hint?

Inside apply, this refers to the guest object. Use this.favoriteDrink = "Lemonade".

3
Use let with it receiver to print a message
Use the let function on the guest variable to print the message "Alice's favorite drink is Lemonade". Inside let, use it.name and it.favoriteDrink to build the message.
Kotlin
Need a hint?

Inside let, it refers to the guest object. Use println("${it.name}'s favorite drink is ${it.favoriteDrink}").

4
Print the updated favorite drink using both receivers
Print two lines: first, use apply on guest to set favoriteDrink to "Orange Juice" using this.favoriteDrink. Then use let on guest to print "Alice now likes Orange Juice" using it.name and it.favoriteDrink.
Kotlin
Need a hint?

First use apply to update the drink, then let to print the message.