Aditya Patil
Aditya Patil

Reputation: 1486

How to convert below line from Java to Kotlin

dots = new TextView[layouts.length];

Suggested by Kotlin

dots = arrayOfNulls<TextView>(layouts.size)

and after converting there is error Type Miss match

Required: Array<TextView>

Found: Array<TextView?>

Upvotes: 0

Views: 424

Answers (4)

Alexey Romanov
Alexey Romanov

Reputation: 170723

If it's initialized by something like

dots = new TextView[layouts.length];
for (int i = 0; i < layouts.length; i++) {
    dots[i] = ... // does something with i
}

so afterwards you know it contains no nulls, then it should be typed as Array<TextView> and initialized as

dots = Array<TextView>(layouts.length) { i -> ... }

Otherwise, if it can still contain nulls later when used, change the type to Array<TextView?>.

Upvotes: 0

ChandraShekhar Kaushik
ChandraShekhar Kaushik

Reputation: 397

you can use it like below:-

val dots: Array<TextView?> = arrayOfNulls(layouts.size)

Here ? means it can be null.

Before you have your data type as

Array<TextView>

Upvotes: 0

a_local_nobody
a_local_nobody

Reputation: 8191

dots = arrayListOf<TextView>() that's how you would do it for kotlin for an empty arraylist with non-null values or

arrayOfNulls<TextView?>(layouts.size) is for an array of nulls

Upvotes: 2

Rutger
Rutger

Reputation: 134

You are getting this error because an arrayOfNulls contains the number of given elements as a "null" object. But TextView is only nullable when you write it like TextView?. You can filter dots if you would like to remove to null values when you have filled it with your data by something like dots.filterNotNull()

Upvotes: 0

Related Questions