Jocky Doe
Jocky Doe

Reputation: 2161

Two dimensional generic Array provider

I'm trying to implement generic two dimensional array provider in Kotlin:

public fun <T> array2dim(sizeOuter: Int, sizeInner: Int): Array<Array<T>>
            = Array(sizeOuter) { Array(sizeInner) }

but can't figure out how to overcome the issue.

The compiler says: Type interface failed: Not enough information to infer parameter T in constructor Array ( size: Int, init: (Int) → T ) Please specify it explicitly.

Upvotes: 2

Views: 152

Answers (1)

zsmb13
zsmb13

Reputation: 89588

First, your inner Array constructor call is missing its second init parameter, the lambda where you create the initial elements that the Array will contain. If you, say, want to fill it all with the same element, you could pass that as a parameter:

fun <T> array2dim(sizeOuter: Int, sizeInner: Int, element: T): Array<Array<T>>
            = Array(sizeOuter) { Array(sizeInner) { element } }

You could also use the outer and inner indexes and create initial elements based on those:

fun <T> array2dim(sizeOuter: Int, 
                  sizeInner: Int, 
                  createElement: (Int, Int) -> T): Array<Array<T>>
        = Array(sizeOuter) { outerIndex ->
              Array(sizeInner) { innerIndex ->
                  createElement(outerIndex, innerIndex)
              } 
          }

If you have nothing to initialize your Array with when you create it, consider creating nullable inner Arrays with arrayOfNulls.


These will still give you an error about not being able to access T - see this answer to a related question for the explanation, but you'll need to mark your T as reified (and consequently, your function as inline):

inline fun <reified T> array2dim(sizeOuter: Int, sizeInner: Int, element: T)
            : Array<Array<T>>
            = Array(sizeOuter) { Array(sizeInner) { element } }

Upvotes: 4

Related Questions