Primary constructor and init blocks
📖 Scenario: Imagine you are creating a simple program to represent a book in a library system. Each book has a title and an author. You want to use Kotlin's primary constructor and init blocks to set up the book details and print a welcome message when a book object is created.
🎯 Goal: Build a Kotlin class called Book that uses a primary constructor to accept title and author. Use an init block to print a message confirming the book creation with its title and author.
📋 What You'll Learn
Create a class named
Book with a primary constructor that takes title and author as parameters.Use an
init block inside the class to print a message: "Book created: [title] by [author]".Create an instance of
Book with the title "1984" and author "George Orwell".Print the message from the
init block automatically when the object is created.💡 Why This Matters
🌍 Real World
Classes with primary constructors and init blocks are used to create objects with initial setup in many Kotlin applications like Android apps or backend services.
💼 Career
Understanding primary constructors and init blocks is essential for Kotlin developers to write clean and efficient code that initializes objects properly.
Progress0 / 4 steps