0
0
Kotlinprogramming~30 mins

Secondary constructors in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Secondary Constructors in Kotlin
📖 Scenario: You are creating a simple Kotlin class to represent a Book in a library system. Sometimes you know all the details about the book, and sometimes you only know the title and author.
🎯 Goal: Build a Kotlin class Book with a primary constructor and a secondary constructor to handle different ways of creating book objects.
📋 What You'll Learn
Create a class called Book with a primary constructor that takes title, author, and year.
Add a secondary constructor that takes only title and author, and sets year to 0.
Create two Book objects using both constructors.
Print the details of both books.
💡 Why This Matters
🌍 Real World
Secondary constructors let you create objects in different ways depending on the information you have, like when some details are missing or optional.
💼 Career
Understanding constructors is essential for Kotlin developers to write flexible and readable code, especially when working with data models in apps.
Progress0 / 4 steps
1
Create the Book class with a primary constructor
Create a Kotlin class called Book with a primary constructor that has three parameters: title of type String, author of type String, and year of type Int. Store these parameters as properties in the class.
Kotlin
Need a hint?

Use class Book(val title: String, val author: String, val year: Int) to create the class with properties.

2
Add a secondary constructor to the Book class
Inside the Book class, add a secondary constructor that takes only title and author as parameters. This constructor should call the primary constructor and set year to 0.
Kotlin
Need a hint?

Use constructor(title: String, author: String) : this(title, author, 0) inside the class.

3
Create two Book objects using both constructors
Create a variable called book1 using the primary constructor with "1984", "George Orwell", and 1949. Then create a variable called book2 using the secondary constructor with "Animal Farm" and "George Orwell".
Kotlin
Need a hint?

Use val book1 = Book("1984", "George Orwell", 1949) and val book2 = Book("Animal Farm", "George Orwell").

4
Print the details of both books
Print the details of book1 and book2 in the format: Title: [title], Author: [author], Year: [year]. Use two separate println statements.
Kotlin
Need a hint?

Use println("Title: ${book1.title}, Author: ${book1.author}, Year: ${book1.year}") and similarly for book2.