0
0
Kotlinprogramming~30 mins

Why extensions add without modifying in Kotlin - See It in Action

Choose your learning style9 modes available
Why Extensions Add Without Modifying in Kotlin
📖 Scenario: Imagine you have a simple class representing a book in a library app. You want to add a new feature to get a short description of the book without changing the original class code.
🎯 Goal: You will learn how to use Kotlin extensions to add new functions to an existing class without modifying its original code.
📋 What You'll Learn
Create a class called Book with two properties: title and author
Create an extension function called shortDescription for the Book class
The shortDescription function should return a string combining the title and author
Call the shortDescription function on a Book object and print the result
💡 Why This Matters
🌍 Real World
Extensions let developers add new features to existing classes from libraries or frameworks without changing their source code. This helps keep code clean and flexible.
💼 Career
Knowing how to use Kotlin extensions is useful for Android developers and Kotlin programmers to write cleaner, more maintainable code and extend functionality easily.
Progress0 / 4 steps
1
Create the Book class
Create a class called Book with two properties: title of type String and author of type String. Use a primary constructor to set these properties.
Kotlin
Need a hint?

Use class Book(val title: String, val author: String) to create the class with properties.

2
Create an extension function shortDescription
Create an extension function called shortDescription for the Book class. It should return a String combining the book's title and author in this format: "Title by Author".
Kotlin
Need a hint?

Write fun Book.shortDescription(): String { return "$title by $author" } to add the extension function.

3
Create a Book object and call shortDescription
Create a Book object called myBook with title set to "Kotlin Basics" and author set to "Jane Doe". Then call the shortDescription function on myBook and store the result in a variable called description.
Kotlin
Need a hint?

Create the object with val myBook = Book("Kotlin Basics", "Jane Doe") and call myBook.shortDescription().

4
Print the description
Print the variable description to display the short description of the book.
Kotlin
Need a hint?

Use println(description) to show the result.