0
0
Kotlinprogramming~15 mins

Properties with val and var in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Properties with val and var
📖 Scenario: Imagine you are creating a simple app to store information about a book. Each book has a title and a number of pages.
🎯 Goal: You will create a Kotlin class called Book with properties using val and var. Then you will create an instance of this class and print its details.
📋 What You'll Learn
Create a class named Book with two properties: title and pages.
Make title a val property (cannot be changed after creation).
Make pages a var property (can be changed after creation).
Create an instance of Book with the title "Kotlin Basics" and 200 pages.
Change the number of pages to 250.
Print the book's title and pages.
💡 Why This Matters
🌍 Real World
Understanding <code>val</code> and <code>var</code> is essential for managing data that should or should not change in apps, like user profiles or settings.
💼 Career
Many Kotlin jobs require knowledge of properties to write safe and clear code, especially in Android app development.
Progress0 / 4 steps
1
Create the Book class with properties
Create a Kotlin class called Book with two properties: a val called title of type String and a var called pages of type Int. Use the primary constructor to set these properties.
Kotlin
Need a hint?

Use the primary constructor syntax: class Book(val title: String, var pages: Int).

2
Create an instance of Book
Create a variable called myBook and assign it a new Book object with the title "Kotlin Basics" and pages 200.
Kotlin
Need a hint?

Use val myBook = Book("Kotlin Basics", 200) to create the instance.

3
Change the pages property
Change the pages property of myBook to 250.
Kotlin
Need a hint?

Use myBook.pages = 250 to update the pages.

4
Print the book details
Print the title and pages of myBook using println. Use this exact format: "Title: Kotlin Basics, Pages: 250".
Kotlin
Need a hint?

Use println("Title: ${myBook.title}, Pages: ${myBook.pages}") to print the details.