0
votes

I have this code

 var str : CharArray


var t =0
for (k in i..i+3) {
    str[t++] = array[k][j]

and it says str must be initialized, i don't know how to initialize.

I tried to initialize like this, but it says type mismatch,

var array: Array<CharArray> = arrayOf("India");

Type inference failed. Expected type mismatch: required: Array found: Array

5

5 Answers

4
votes

You can initialize it this way:

var str : CharArray = CharArray(3) //if you know size
var str : CharArray = charArrayOf() //creates empty array
var str : CharArray? = null //makes your array nullable

Or you can use lateinit for initializing later

0
votes

If you declare your CharArray as it, you must initialize it immediately. Otherwise you can specify that you will initialized it later with the property lateinit, or you can declare your variable as a CharArray and set it to null, or you can use a

var str : CharArray? = null
var lateinit str: CharArray
0
votes

You have declared a variable of type CharArray, but haven't assigned it with any instance.

Before you can set elements of that CharArray, you have to create an instance of CharArray. It looks like you know the size of that array in advance, then you can use the following array constructor:

// creates an instance of CharArray of 4 elements, filled with \u0000 chars
val str = CharArray(4)  

// after that you can set elements in the array

Bonus point: if you have a function that can provide an array element value given its index you can use the similar constructor to create instance and initialized its elements at once:

val str = CharArray(4) { index -> 
    array[i + index][j]
}
0
votes

There are many ways to initialize arrays in Kotlin. The easiest, if all values are the same (here I'm using blanks), is this:

var chars = CharArray(26) { ' ' }

If you have a specific set of characters (here I made it a constant), I found this to be an easy way:

val CHARS = "abcdefghijklmnopqrstuvwxyz".toCharArray()

If you want to copy one to another (clone), you can do this:

val array2 = CharArray(array.size) { i -> array[i] }

In the example you gave above, you're trying to initialize an array of CharArray. Not sure if that's what you really want, but you can do it this way (I have an array of 25 items, each of which is an array with 5 blanks):

var array2D = Array<CharArray>(25) { CharArray(5) { ' ' } } 
0
votes

it says str must be initialized. The problem is that you did not completely define the structure of the char array you intend to create. The CharArray requires knowing the actual length or size of the array you're creating. So in this note, you need to initialize it before trying to populate it. my code snippet is down .....Your code still has some issues with it.

var str : CharArray = CharArray(9)


var t = 0
for (k in 1..9) {
    str[t] = k
}

The output::: values from 1 to 30 will be stored in the str character array