Generic function with generic 2D array

2020-07-27 05:12发布

问题:

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:

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.