0
0
Kotlinprogramming~20 mins

Companion vs top-level functions decision in Kotlin - Hands-On Comparison

Choose your learning style9 modes available
Deciding Between Companion and Top-Level Functions in Kotlin
📖 Scenario: You are building a simple Kotlin program to manage a library of books. You want to organize your functions properly to keep your code clean and easy to understand.
🎯 Goal: Learn when to use companion object functions and when to use top-level functions by creating a Book class with a companion object and a top-level function to display book details.
📋 What You'll Learn
Create a Book class with a property title of type String
Add a companion object inside the Book class with a function createSampleBook() that returns a Book instance with the title "Sample Book"
Create a top-level function printBookTitle(book: Book) that prints the book's title
Call the companion object function and the top-level function to show their usage
💡 Why This Matters
🌍 Real World
Organizing code in Kotlin projects to keep related functions inside classes and general helpers outside helps maintain clean and readable code.
💼 Career
Understanding companion objects and top-level functions is important for Kotlin developers to write idiomatic and maintainable code in Android or backend projects.
Progress0 / 4 steps
1
Create the Book class
Create a class called Book with a property title of type String.
Kotlin
Need a hint?

Use class Book(val title: String) to create the class with a property.

2
Add a companion object with a factory function
Inside the Book class, add a companion object with a function called createSampleBook() that returns a Book instance with the title "Sample Book".
Kotlin
Need a hint?

Use companion object inside the class and define fun createSampleBook() that returns Book("Sample Book").

3
Create a top-level function to print the book title
Create a top-level function called printBookTitle that takes a Book parameter named book and prints its title property.
Kotlin
Need a hint?

Define a function printBookTitle outside the class that prints book.title.

4
Use the companion and top-level functions
Call the companion object function Book.createSampleBook() to create a book, then call the top-level function printBookTitle with that book. Print the output.
Kotlin
Need a hint?

Use val sampleBook = Book.createSampleBook() and then printBookTitle(sampleBook) inside main().