Create random instance from a class. It
uses kotlin-reflect
to create by reflection the instance. (Using KClass
and KType)
Reflection is a set of language and library features that allows for introspecting the structure of your own program at runtime.
Based on Marcin Moskala from Kt Academy 's article:
To use the packages hosted on the GPR (GitHub Package Registry) you need your username/token. Add the GPR as a repository inside your build.gradle.kts:
maven {
url = uri("https://maven.pkg.github.com/sylhare/RandomK")
credentials {
username = project.findProperty("gpr.user") as String? ?: System.getenv("USERNAME")
password = project.findProperty("gpr.key") as String? ?: System.getenv("TOKEN")
}
}
You can set those variables using:
export USERNAME="my-github-username"
export TOKEN="my-secret-personal-access-token-for-github"
Then add the randomK dependency:
dependencies {
implementation("com.github.sylhare:randomk:$randomKVersion")
}
With the latest version available, check out the package section 😉
Find the full example here.
Since we're using typeOf<T>()
fom kotlin-reflect to detect the retention type (introduced in kotlin v1.3), the library
is under the @ExperimentalStdlibApi
.
You can create a random instance with randomK
like:
private val example: Example = randomK()
private val otherExample = randomK<OtherExample>()
It will create a random instance.