Skip to content

Instantly share code, notes, and snippets.

@aroranubhav
Created March 3, 2025 20:35
Show Gist options
  • Save aroranubhav/4ecd858280d2552a0d7e641ec498ad3f to your computer and use it in GitHub Desktop.
Save aroranubhav/4ecd858280d2552a0d7e641ec498ad3f to your computer and use it in GitHub Desktop.
Classs Instance Via Factory
fun interface Factory<T> {
fun create(): T
}
fun <T> createInstance(factory: Factory<T>): T {
return factory.create()
}
fun main() {
val instance = createInstance(Factory {
return@Factory FirstClass(SecondClass())
})
instance.callSecondClassMethod()
}
class FirstClass(
private val secondClass: SecondClass
) {
fun callSecondClassMethod() {
secondClass.doWork()
}
}
class SecondClass {
fun doWork() {
for (i in 1..10) {
println(Random.nextInt(1, 10))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment