0
0
Kotlinprogramming~30 mins

Named companion objects in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the Book class with properties
Create a Kotlin class called Book with two val properties: title and author, both 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
Add a named companion object called Factory
Inside the Book class, add a named companion object called Factory.
Kotlin
Need a hint?

Write companion object Factory { } inside the class.

3
Add a fromString function inside Factory
Inside the named companion object Factory, add a function called fromString that takes a String parameter named data and returns a Book. The function should split data by " - " and use the parts to create and return a new Book.
Kotlin
Need a hint?

Use data.split(" - ") to separate title and author, then return a new Book.

4
Create a Book using Factory and print details
Use the named companion object Factory to create a Book from the string "The Hobbit - J.R.R. Tolkien". Store it in a variable called book. Then print the book's title and author in the format: Title: The Hobbit, Author: J.R.R. Tolkien.
Kotlin
Need a hint?

Call Book.Factory.fromString("The Hobbit - J.R.R. Tolkien") and print the properties.