0
0
Kotlinprogramming~15 mins

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

Choose your learning style9 modes available
Understanding the Kotlin also Function
📖 Scenario: Imagine you are organizing a list of books and want to log some information while building the list. Kotlin's also function helps you do extra actions on an object without changing it.
🎯 Goal: You will create a list of book titles, use the also function to print each book as it is added, and finally print the full list.
📋 What You'll Learn
Create a mutable list of strings called books with initial titles
Create a variable newBook with a book title
Use the also function to print the newBook before adding it to books
Print the final books list
💡 Why This Matters
🌍 Real World
The <code>also</code> function is useful when you want to do extra work with an object, like logging or debugging, without changing the object itself.
💼 Career
Understanding <code>also</code> helps you write cleaner Kotlin code, which is valuable for Android development and backend Kotlin projects.
Progress0 / 4 steps
1
Create the initial list of books
Create a mutable list of strings called books with these exact titles: "Kotlin Basics", "Advanced Kotlin", and "Kotlin Coroutines".
Kotlin
Need a hint?

Use mutableListOf to create a list you can add to later.

2
Create a new book title variable
Create a variable called newBook and set it to the string "Kotlin Flow".
Kotlin
Need a hint?

Use val to create a read-only variable with the exact string.

3
Use also to print the new book before adding
Use the also function on newBook to print "Adding book: " followed by the book title, then add the book to the books list.
Kotlin
Need a hint?

The also function lets you do something with the object (like print) and then returns it so you can add it to the list.

4
Print the final list of books
Write a println statement to print the books list.
Kotlin
Need a hint?

Use println(books) to show the full list after adding the new book.