1
votes

I'd like to create a custom Array in Kotlin.

class Node(val point: Point) {
    var neighbour : Array<Node?> = Array(4, {_ -> null})
    var prev : Byte = -1
}

Now, in another class, I tried to create an object like:

class OtherClass{
    var field: Array<Array<Node?>> = Array(size.x, {_ -> Array(size.y, {_ -> null})})
    }

So basically, I need a Grid of Nodes, all initialized with null. The provided sizes are of type Integer.

I get the following error:
Type inference failed. Expected type mismatch:
required: Array< Array< Node?>>
found: Array< Array< Nothing?>

2

2 Answers

6
votes

Kotlin has an arrayOfNulls function which might make this a bit more elegant:

val field: Array<Array<Node?>> = Array(4) { arrayOfNulls<Node?>(4) }

Or, without optional types:

val field  = Array(4) { arrayOfNulls<Node?>(4) }

I still have to specify Node? as the innermost type, however.

2
votes

Okay, the solution was quite simple:

var field: Array<Array<Node?>> = Array(size.x, {_ -> Array(size.y, {_ -> null as Node?})})