Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Array creation: No value passed for parameter 'init' [duplicate]

I am converting a Java file into Kotlin in Android Studio and I am getting this error:

No value passed for parameter 'init'

I modified the code slightly by adding lateinit

The java code is:

 private TextView[] dots;
 private int[] layouts;

private void addBottomDots(int currentPage)
{
    dots = new TextView[layouts.length]; 
    //some lines here
}

And corresponding Kotlin code is

private lateinit var dots: Array<TextView>
private lateinit var layouts: IntArray

private fun addBottomDots(currentPage: Int)
    {
       dots = Array<TextView>(layouts.size) // error happens here
       // some lines here

    }

As I am new in Kotlin, I can't figure out why this is the reason

like image 748
rarahat02 Avatar asked Jan 29 '23 18:01

rarahat02


2 Answers

Check the Array constructor: public inline constructor(size: Int, init: (Int) -> T) - that's why error happens.

Guess you want to create ArrayList

dots = ArrayList<TextView>(layouts.size)
like image 161
GuessWho Avatar answered Jan 31 '23 07:01

GuessWho


The code is not equivalent. Your original code actually represents the type var dots: Array<TextView?> since the values of the array may be uninitialized.

Because you defined it as non-null, the only available constructor for Array requires a function to initialize all elements to a non-null value. You can either provide this or change the type to be nullable and use dots = arrayOfNulls(layouts.size)

like image 33
Kiskae Avatar answered Jan 31 '23 07:01

Kiskae