4

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

hotkey
  • 140,743
  • 39
  • 371
  • 326
ruhulrahat
  • 1,325
  • 4
  • 15
  • 23

2 Answers2

6

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)
GuessWho
  • 664
  • 1
  • 6
  • 19
3

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)

Kiskae
  • 24,655
  • 2
  • 77
  • 74
  • You are right, I changed this code slightly. But where is the problem in here? – ruhulrahat Feb 01 '18 at 14:52
  • You are creating an array of non-null values without providing the non-null values. – Marko Topolnik Feb 01 '18 at 14:53
  • The problem exists because Kotlin requires strict nullability in its types. By default Java arrays are filled with `null` so they cannot be anything but arrays of a nullable type. To safely create non-nullable arrays the library provides ways to ensure it is immediately filled with non-null values to satisfy the non-null requirement. – Kiskae Feb 01 '18 at 14:56
  • Then what should I change in code? I instantiated layout variable in oncreate() method @MarkoTopolnik – ruhulrahat Feb 01 '18 at 15:01
  • Can all the elements be initialized when the array is created? Then use the non-nullable constructor to initialize it all at once. Are they only progressively available? Then you have no choice but to use a nullable array and checking during access to ensure null safety. – Kiskae Feb 01 '18 at 15:07
  • it's correct answer – Abror Esonaliev Nov 29 '18 at 07:42