How to create a generic array filled with nulls in Kotlin?

前端 未结 4 1808
日久生厌
日久生厌 2021-02-14 02:33

I tried this, and the code didn\'t compile.

class GenericClass() {
    private var arr : Array? = null

    {
        arr = Array(10,          


        
4条回答
  •  旧巷少年郎
    2021-02-14 02:56

    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()
    }
    

提交回复
热议问题