Using Named Companion Objects in Kotlin
📖 Scenario: Imagine you are creating a simple app that manages books. Each book has a title and an author. You want to add a special helper inside the Book class that can create a book from a single string with the format "title - author".
🎯 Goal: You will create a Kotlin class Book with a named companion object called Factory. This companion object will have a function to create a Book from a string. Finally, you will print the book details.
📋 What You'll Learn
Create a Kotlin class named
Book with two properties: title and author.Add a named companion object called
Factory inside the Book class.Inside
Factory, create a function fromString that takes a single String parameter and returns a Book.Use the
fromString function to create a Book from a string formatted as "title - author".Print the book's title and author.
💡 Why This Matters
🌍 Real World
Named companion objects help organize helper functions related to a class, like factory methods, making code cleaner and easier to understand.
💼 Career
Understanding companion objects is important for Kotlin developers, especially when working on Android apps or backend services where factory methods and static-like helpers are common.
Progress0 / 4 steps