2

How can one implement a generic function which creates an empty generic 2D array? In the following code sample an empty 1D array is created and has the expected type. However, when I call test2D I get an error:

java.lang.ClassCastException: [[Ljava.lang.Object; cannot be cast to [[Ljava.lang.Integer;

inline fun <reified T> make1D(mask: Array<T>) : Array<T> {
  val res : Array<T> = arrayOf()
  return res
}

@Test
fun test1D() {
  val a : Array<Int> = arrayOf(0)
  val b : Array<Int> = make1D(a)
  assertEquals(0, b.size)
}

inline fun <reified T> make2D(mask: Array<Array<T>>) : Array<Array<T>> {
  val res : Array<Array<T>> = arrayOf() 
  // I expect T to be equal to Int when calling from test below, 
  // and res to have Integer[][] type;
  // however it has Object[][] type instead
  return res
}

@Test
fun test2D() {
  val a : Array<Array<Int>> = arrayOf(arrayOf(0))
  val b : Array<Array<Int>> = make2D(a)
  assertEquals(0, b.size)
}
1

1 Answer 1

1

I think you are one level too deep for the reified parameter. Maybe it is a bug, creating a YouTrack issue will help to find out. This code works when you let T be the whole inner array:

inline fun <reified T> make2D(mask: Array<T>): Array<T> {
    val res: Array<T> = arrayOf<T>()
    return res
}

@Test
fun test2D() {
    val a: Array<Array<Int>> = arrayOf(arrayOf(0))
    val b: Array<Array<Int>> = make2D(a)
    assertEquals(0, b.size)
}

After you create a YouTrack issue, please post the issue number here for tracking.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.