0
0
Kotlinprogramming~15 mins

Creating instances without new keyword in Kotlin - Try It Yourself

Choose your learning style9 modes available
Creating instances without new keyword
📖 Scenario: Imagine you are building a simple app to manage books in a library. You want to create book objects to store information about each book.
🎯 Goal: You will create instances of a Book class without using the new keyword, which is not used in Kotlin. You will then print the details of the book.
📋 What You'll Learn
Create a data class called Book with properties title and author
Create an instance of Book without using new
Print the book details using string interpolation
💡 Why This Matters
🌍 Real World
Creating instances without the <code>new</code> keyword is common in Kotlin and many modern languages. It makes code cleaner and easier to read.
💼 Career
Understanding how to create and use class instances is fundamental for Kotlin developers working on Android apps, backend services, or any Kotlin-based projects.
Progress0 / 4 steps
1
Create the Book data class
Create a Kotlin data class called Book with two properties: title of type String and author of type String.
Kotlin
Need a hint?

Use the data class keyword to create a simple class with properties.

2
Create a Book instance
Create a variable called myBook and assign it an instance of Book with the title "The Hobbit" and author "J.R.R. Tolkien". Do not use the new keyword.
Kotlin
Need a hint?

In Kotlin, you create instances by calling the class name like a function without new.

3
Access properties of the Book instance
Create a variable called bookTitle and assign it the title property of myBook. Also create a variable called bookAuthor and assign it the author property of myBook.
Kotlin
Need a hint?

Use dot notation to access properties of an instance.

4
Print the book details
Print the text "Title: The Hobbit, Author: J.R.R. Tolkien" using the variables bookTitle and bookAuthor with string interpolation.
Kotlin
Need a hint?

Use println and $variableName inside a string to insert variable values.