Kotlin
Project design
Design the skeleton of the intermediate final mini app.
Project: Library app
In this five-lesson project you will build a library console app. Each lesson adds one piece, and by the final lesson you will have an app that combines OOP + collections + Flow + file I/O.
You will use what you learned in previous groups: data class for data modeling, sealed class for hierarchy, MutableList for collection management, java.io.File for file I/O and Flow for async streams. In the first lesson you will define the Book data class and its format method.
The Book data class
To represent a book in a library you will define data class Book. A data class generates equals, hashCode, toString and copy. The book will have a title, an author and a publication year.
data class Book(
val title: String,
val author: String,
val year: Int
) {
fun format(): String = "$title - $author ($year)"
}
The format method returns a readable string: Crime and Punishment - Dostoyevsky (1866). This will be used when printing the book to the screen and saving it to a file. Later lessons will add a category property and extend format.
Exercise Define the Book data class
Define data class Book(val title: String, val author: String, val year: Int). Inside it add fun format(): String = "$title - $author ($year)". In main create val b = Book("Crime and Punishment", "Dostoyevsky", 1866) and print with println(b.format()).
Show example solution
data class Book(val title: String, val author: String, val year: Int) {
fun format(): String = "$title - $author ($year)"
}
fun main() {
val b = Book("Crime and Punishment", "Dostoyevsky", 1866)
println(b.format())
}
Test yourself
-
What is defined in the first lesson of the library project?
- A Flow stream
- The Library class
- The Book data class
- File saving
Show answer
The Book data class — The first lesson defines the Book data class and its format method.
-
The data class keyword
____ class Book(val title: String, val author: String, val year: Int)
Show answer
data class Book(val title: String, val author: String, val year: Int)
-
Match the Book parts
- data class Book
- Data class
- val title
- Title
- val year
- Publication year
- format()
- Readable output
Next lesson: OOP model