CodeBlanks Logo Icon CodeBlanks

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.

Practice 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()).

Starter code

Main.kt
// Define a Book data class: title (String), author (String), year (Int)
// format method: returns "{title} - {author} ({year})"
// main: create a Book instance and print format output with println
fun main() {
    // write here
}

Sample solution

Main.kt
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())
}

Expected output

Crime and Punishment - Dostoyevsky (1866)

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is defined in the first lesson of the library project?

  • A Flow stream
  • The Library class
  • The Book data class Correct answer
  • File saving

Explanation: The first lesson defines the Book data class and its format method.

2 The data class keyword

Question
____ class Book(val title: String, val author: String, val year: Int)
Answer
data class Book(val title: String, val author: String, val year: Int)

Explanation: data class Book declares a data class.

3 Match the Book parts

Term Meaning
data class Book Data class
val title Title
val year Publication year
format() Readable output

All lessons in Intermediate