0
0
Kotlinprogramming~15 mins

Chaining scope functions in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Chaining scope functions
📖 Scenario: You are organizing a small library system. You want to create a book record, update its details, and then display the final information.
🎯 Goal: Build a Kotlin program that creates a Book data class instance, uses chaining of scope functions to update its properties, and then prints the updated book details.
📋 What You'll Learn
Create a Book data class with title, author, and year properties
Create an instance of Book with initial values
Use chaining of scope functions apply and also to update the book's year and print a message
Print the final updated book details
💡 Why This Matters
🌍 Real World
Chaining scope functions helps write clean and readable code when updating objects and performing related actions, common in app development.
💼 Career
Understanding Kotlin scope functions and chaining is valuable for Android developers and Kotlin programmers to write concise and maintainable code.
Progress0 / 4 steps
1
Create the Book data class and initial book
Create a Kotlin data class called Book with properties title (String), author (String), and year (Int). Then create a variable myBook and assign it a Book instance with title "The Kotlin Guide", author "Anna", and year 2020.
Kotlin
Need a hint?

Remember to use var for year because it will change later.

2
Add a variable for the new publication year
Create a variable called newYear and set it to 2023.
Kotlin
Need a hint?

Just create a simple val with the number 2023.

3
Chain apply and also to update and print
Use chaining of scope functions on myBook: first use apply to update the year property to newYear, then use also to print the message "Updated book year to 2023".
Kotlin
Need a hint?

Use apply to change year, then also to print the message.

4
Print the final updated book details
Write a println statement to print myBook so it shows the updated book details.
Kotlin
Need a hint?

Just print myBook to see the updated details.