Created
September 29, 2025 20:05
-
-
Save madnotdead/6bb2982f907173d32619e486b437c437 to your computer and use it in GitHub Desktop.
Generic repository implementation in Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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