I tried this, and the code didn\'t compile.
class GenericClass() {
private var arr : Array? = null
{
arr = Array(10,
If you need to initialize array in the constructor, you can add an inline factory method and parametrize it using reified T
. This solution is inspired by answer https://stackoverflow.com/a/41946516/13044086
class GenericClass protected constructor(
private val arr : Array
) {
companion object {
inline fun create(size: Int) = GenericClass(arrayOfNulls(size))
}
}
fun main() {
val strs = GenericClass.create(10)
...
}
Notice that the constructor is protected, because inline function can't access a private constructor.
If you need to create an array after the object is created, you can pass lambda that creates the array into the method. Lambda can be created inside of extension function, so information about type of the array is preserved. @PublishedApi
annotation is used to encapsulate private method fill
.
import GenericClass.Companion.fill
class GenericClass {
private var arr : Array? = null
fun show() {
print(arr?.contentToString())
}
private fun fill(arrayFactory: (size: Int) -> Array) {
this.arr = arrayFactory(10)
}
@PublishedApi
internal fun `access$fill`(arrayFactory: (size: Int) -> Array) = fill(arrayFactory)
companion object {
inline fun GenericClass.fill() {
`access$fill`(arrayFactory = { size -> arrayOfNulls(size) })
}
}
}
fun main() {
val strs = GenericClass()
strs.fill()
strs.show()
}