0
0
Kotlinprogramming~15 mins

Inner class access to outer members in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Inner class access to outer members
📖 Scenario: Imagine you are creating a simple app to manage a library. You want to keep track of a Book and its Details like title and author. The Details class is inside the Book class as an inner class.
🎯 Goal: You will create a Book class with an inner class Details. The inner class will access the outer class's properties to print the full book information.
📋 What You'll Learn
Create a class called Book with a property name of type String
Inside Book, create an inner class Details with a property author of type String
In Details, write a function printInfo() that prints the book name and author using the outer class's name property
Create an instance of Book and its inner class Details, then call printInfo() to show the output
💡 Why This Matters
🌍 Real World
Inner classes help organize related code together, like keeping book details inside a book class, making code easier to read and maintain.
💼 Career
Understanding inner classes is useful for Kotlin developers working on Android apps or backend services where encapsulation and clear structure are important.
Progress0 / 4 steps
1
Create the outer class with a property
Create a class called Book with a property name of type String and set it to "Kotlin Programming".
Kotlin
Need a hint?

Use class Book { val name: String = "Kotlin Programming" } to create the class and property.

2
Add an inner class with a property
Inside the Book class, create an inner class Details with a property author of type String set to "John Doe".
Kotlin
Need a hint?

Use inner class Details { val author: String = "John Doe" } inside Book.

3
Add a function in inner class to print book info
In the Details inner class, add a function printInfo() that prints the book name and author using println. Access the outer class's name property with this@Book.name.
Kotlin
Need a hint?

Use fun printInfo() { println("Book: ${this@Book.name}, Author: $author") } inside Details.

4
Create instances and call the function
Create an instance of Book called book. Then create an instance of the inner class Details called details from book. Finally, call details.printInfo() to display the book information.
Kotlin
Need a hint?

Create val book = Book(), then val details = book.Details(), then call details.printInfo().