CodeBlanks Logo Icon CodeBlanks

Model design

Design the skeleton of Book and Member data classes.

Project: Library app

In this five-lesson project you will build a library application. Each lesson adds one piece, and by the final lesson book and member management, checkout, search and command handling come together.

You will use data class from previous groups to define data classes. In the first lesson you define two models: Book with three fields and Member with two fields. Both are written as data class, so toString is generated automatically and println gives readable output.

Book and Member fields

The Book model carries three properties: title, author and isbn. All are of type String and cannot be empty.

The Member model carries two properties: name and id. Example definition: data class Member(val name: String, val id: String). When an instance is printed with println, it produces readable output like Member(name=Alex, id=M1). You will use this output for testing in later lessons.

Practice Define the Book and Member models

Define data class Book(val title: String, val author: String, val isbn: String) and data class Member(val name: String, val id: String). In main create Book("War and Peace", "Tolstoy", "978-1") and Member("Alex", "M1") instances and print each with println.

Starter code

Main.kt
fun main() {
    // Create Book and Member instances and print with println
}

// Define the Book data class: title, author, isbn (all String)
// Define the Member data class: name, id (all String)

Sample solution

Main.kt
data class Book(val title: String, val author: String, val isbn: String)
data class Member(val name: String, val id: String)

fun main() {
    val b = Book("War and Peace", "Tolstoy", "978-1")
    val m = Member("Alex", "M1")
    println(b)
    println(m)
}

Expected output

Book(title=War and Peace, author=Tolstoy, isbn=978-1)
Member(name=Alex, id=M1)

Questions and answers

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

1 Which line correctly defines the Book model?

  • data class Book(title: String, author: String, isbn: String)
  • class Book(val title: String, val author: String, val isbn: String)
  • data class Book(val title: String, val author: String, val isbn: String) Correct answer
  • data class Book(val title, val author, val isbn)

Explanation: With the data modifier and val parameters the Book data class is defined correctly.

2 Complete the Member data class

Question
data class Member(val name: String, val ____: String)
Answer
data class Member(val name: String, val id: String)

Explanation: The Member class carries name and id properties.

3 Match the model fields

Term Meaning
Book.title Book title
Book.isbn Book number
Member.name Member name
Member.id Member number

All lessons in Intermediate