0
0
Kotlinprogramming~15 mins

Primary constructor and init blocks in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the Book class with primary constructor
Create a Kotlin class called Book with a primary constructor that takes two parameters: title of type String and author of type String.
Kotlin
Need a hint?
Use the syntax: class ClassName(val param1: Type, val param2: Type) { }
2
Add an init block to print a message
Inside the Book class, add an init block that prints the message: "Book created: [title] by [author]" using the constructor parameters.
Kotlin
Need a hint?
Use an init block and println with string interpolation to show the message.
3
Create an instance of Book
Create a variable called myBook and assign it a new Book object with the title "1984" and author "George Orwell".
Kotlin
Need a hint?
Use val myBook = Book("1984", "George Orwell") to create the object.
4
Run the program to see the output
Run the program and observe the output printed by the init block when myBook is created.
Kotlin
Need a hint?
The message should print automatically when the object is created.