0
0
Kotlinprogramming~20 mins

With function behavior and use cases in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Kotlin 'with' Function for Cleaner Code
📖 Scenario: You are creating a simple program to manage a book's details. You want to update and display the book's information in a clean and readable way.
🎯 Goal: Build a Kotlin program that uses the with function to update and print the details of a book object.
📋 What You'll Learn
Create a data class called Book with properties title, author, and year
Create an instance of Book with initial values
Use the with function to update the book's year and print all details inside the with block
Print the book details outside the with block to confirm changes
💡 Why This Matters
🌍 Real World
Using the <code>with</code> function helps keep your code clean and readable when working with objects that need multiple operations.
💼 Career
Understanding <code>with</code> is useful for Kotlin developers to write concise and maintainable code, especially in Android app development and backend services.
Progress0 / 4 steps
1
Create the Book data class and an instance
Create a Kotlin data class called Book with properties title (String), author (String), and year (Int). Then create a variable myBook of type Book with title as "Kotlin Basics", author as "Jane Doe", and year as 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 an Int variable called newYear and set it to 2023.
Kotlin
Need a hint?

Use val newYear = 2023 to create the variable.

3
Use the with function to update and print book details
Use the Kotlin with function with myBook as the receiver. Inside the with block, update the year property to newYear and print the book details in the format: "Title: [title], Author: [author], Year: [year]".
Kotlin
Need a hint?

Inside with(myBook) { }, you can access properties directly without myBook.

4
Print the updated book details outside the with block
Print the book details again outside the with block using println in the same format: "Title: [title], Author: [author], Year: [year]" to confirm the update.
Kotlin
Need a hint?

Use println("Title: ${myBook.title}, Author: ${myBook.author}, Year: ${myBook.year}") to print outside the with block.