Created
March 3, 2025 20:35
-
-
Save aroranubhav/4ecd858280d2552a0d7e641ec498ad3f to your computer and use it in GitHub Desktop.
Classs Instance Via Factory
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
| 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