Richard
04/05/2023, 9:37 PMdata class User(val name: String)
interface UserRepository {
context(UserService.Context)
fun createUser(): User
}
class RealUserRepository : UserRepository {
context(UserService.Context)
override fun createUser() = User("random-string")
}
interface UserService {
class Context private constructor()
companion object {
private val context: Context = Context() // How do I create here?
}
//extension function so it's "protected"
fun <T> UserService.withContext(block: context(Context) () -> T): T = with(context) {
block(this)
}
fun createUser(): User
}
class RealUserService : UserService {
val userRepository: UserRepository = RealUserRepository()
override fun createUser() = withContext {
userRepository.createUser()
}
}
Everything works except the initialization of the Context.
1. Is there another way to accomplish this without context receivers?
2. How do I properly initialize the companion object prop?