CodeBlanks Logo Icon CodeBlanks

Project design

Design the skeleton of the advanced final mini app.

Project: Ktor API + Exposed DB + coroutines

In this five-lesson project you will build a small user service. UserRepo for storage, Api for routing, UsersTable for table abstraction and suspend for concurrent access come together.

This structure mimics Ktor's API layer, Exposed's DB abstraction and coroutines' suspend calls at a small scale. In the first lesson you will create the User data class and the UserRepo skeleton; with save and find methods you will add and look up a user.

The UserRepo skeleton

The first lesson defines the User data class and the UserRepo class. The repo stores users in a list; save adds, find looks up by id.

Example: data class User(val id: Int, val name: String). Inside UserRepo, private val users = mutableListOf<User>(). save(u) appends; find(id) returns the user with matching id. In later lessons you will extend this repo with Api and UsersTable.

Practice Define User and UserRepo

Define a data class User(id: Int, name: String). Write a UserRepo class with private val users = mutableListOf<User>(), methods fun save(u: User) and fun find(id: Int): User?. In main add User(1, "Alex") to the repo and print println(repo.find(1)).

Starter code

Main.kt
// User data class: id and name
// UserRepo: users list, save and find
// in main add a user, find by id and print

Sample solution

Main.kt
data class User(val id: Int, val name: String)

class UserRepo {
    private val users = mutableListOf<User>()
    fun save(u: User) { users.add(u) }
    fun find(id: Int): User? = users.find { it.id == id }
}

fun main() {
    val repo = UserRepo()
    repo.save(User(1, "Alex"))
    println(repo.find(1))
}

Expected output

User(id=1, name=Alex)

Questions and answers

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

1 Which structures are defined in the first lesson?

  • Api and routing
  • User data class and UserRepo Correct answer
  • UsersTable
  • suspend functions

Explanation: The first lesson builds User and UserRepo.

2 Complete the User data class

Question
____ User(val id: Int, val name: String)
Answer
data User(val id: Int, val name: String)

Explanation: data class User auto-generates equals and toString.

3 Match the UserRepo parts

Term Meaning
data class User Data class
mutableListOf<User>() Storage
fun save(u) Add
fun find(id) Find

All lessons in Advanced