Skip to content

Instantly share code, notes, and snippets.

@madnotdead
Created September 29, 2025 20:05
Show Gist options
  • Select an option

  • Save madnotdead/6bb2982f907173d32619e486b437c437 to your computer and use it in GitHub Desktop.

Select an option

Save madnotdead/6bb2982f907173d32619e486b437c437 to your computer and use it in GitHub Desktop.
Generic repository implementation in Kotlin
package com.madnotdead.practices
// some data classes
data class Product(val name: String, val price: Double)
data class User(val name: String, val age: Int)
//generic repository interface
interface Repository<T> {
fun get(key: String) : T?
fun set(key: String, value: T)
fun delete(key: String)
}
//in-memory "storage"
var dataStorage = mutableMapOf<String, Any?>()
//Generic repository implementation
class InMemoryRepository<T> : Repository<T> {
override fun get(key: String): T? {
return dataStorage.getOrDefault(key, null) as T?
}
override fun set(key: String, value: T) {
dataStorage[key] = value
}
override fun delete(key: String) {
dataStorage.remove(key)
}
}
//test object
object RepositoryStruct {
val userRepository = InMemoryRepository<User>()
val productRepository = InMemoryRepository<Product>()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment