Part 13 / Topic 7 of 7
Putting it together: a generic, type-safe repository
Every tool from this part, aimed at one thing a real backend service genuinely needs: a repository -- a type-safe layer over storage that works for any entity, as long as you can say how to read that entity's own ID.
interface Repository<ID, T> {
fun save(entity: T): T
fun findById(id: ID): T?
fun findAll(): List<T>
fun deleteById(id: ID): Boolean
val count: Int
}
class InMemoryRepository<ID, T>(private val idOf: (T) -> ID) : Repository<ID, T> {
private val store = linkedMapOf<ID, T>() // LinkedHashMap: keeps insertion order
override fun save(entity: T): T {
store[idOf(entity)] = entity
return entity
}
override fun findById(id: ID): T? = store[id]
override fun findAll(): List<T> = store.values.toList()
override fun deleteById(id: ID): Boolean = store.remove(id) != null
override val count: Int get() = store.size
}
data class Customer(val id: String, val name: String, val city: String)
data class Product(val id: String, val name: String, val priceInRupees: Double)
val customers: Repository<String, Customer> = InMemoryRepository { it.id }
customers.save(Customer("C-01", "Asha Kulkarni", "Pune"))
customers.save(Customer("C-02", "Ravi Shah", "Mumbai"))
customers.save(Customer("C-03", "Meera Nair", "Kochi"))
println("Customer count: ${customers.count}")
println("C-02 -> ${customers.findById("C-02")}")
println("C-99 -> ${customers.findById("C-99")}")
val page1 = paginate(customers.findAll(), pageSize = 2, pageNumber = 1)
println("Customers page ${page1.pageNumber}/${page1.totalPages}: ${page1.items.map { it.name }}")
customers.deleteById("C-01")
println("After delete, count: ${customers.count}")
val products: Repository<String, Product> = InMemoryRepository { it.id }
products.save(Product("P-01", "Basmati Rice", 420.0))
products.save(Product("P-02", "Toor Dal", 180.0))
products.save(Product("P-03", "Sunflower Oil", 210.0))
val costliest = products.findAll().maxByOrNull { it.priceInRupees }
println("Costliest product: ${costliest?.name} at ₹${costliest?.priceInRupees}")
Customer count: 3
C-02 -> Customer(id=C-02, name=Ravi Shah, city=Mumbai)
C-99 -> null
Customers page 1/2: [Asha Kulkarni, Ravi Shah]
After delete, count: 2
Costliest product: Basmati Rice at ₹420.0
InMemoryRepository<ID, T> is written exactly once, against ID and T, and plugged in for two
completely unrelated entity shapes (Customer, Product) just by changing the idOf lambda --
the same Page<T>/paginate from Section 1 works unchanged on either one. A real service would
swap InMemoryRepository for a database-backed implementation of the same Repository<ID, T>
interface; the calling code wouldn't need to change at all.
Full program: examples/07_generic_repository.kt.
Done here? The practice set for Part 13 — including the solutions — is on the part page.