How to get ResultSet string array?

3.7k Views Asked by At

I have a query that is hitting a table that has an array column. When I am processing my records I would like to take the array column's data and treat it like a string array and grab the first value. I had assumed I could do the following:

while (resultSet.next()) {
    val clients = resultSet.getArray("clients")
    println(clients[0])
}

But when I do this I get the error:

Error:(34, 3) Kotlin: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: @InlineOnly public operator inline fun <@OnlyInputTypes K, V> Map.get(key: Int): ??? defined in kotlin.collections @SinceKotlin public operator fun MatchGroupCollection.get(name: String): MatchGroup? defined in kotlin.text

getArray returns type Array! so I had assumed I could access values by index. What do I have to do to access this array of values?

1

There are 1 best solutions below

0
On

Actually, getArray returns a java.sql.Array.

This is not the same as the kotlin.Array type.

You can use getArray on the java.sql.Array, which would simply be translated to array in Kotlin:

resultSet.getArray("clients").array

to get the actual array as an Object/Any.

You can cast it to an Array<out Any?>:

val arr = resultSet.getArray("clients").array as Array<out Any?>

or to the desired type directly, though you may get some ClassCastExceptions as a result.

To stay type-safe, you may want something like

val firstClient = (resultSet.getArray("clients").array as? Array<out Any?>)
        ?.filterIsInstance<String>()
        ?.firstOrNull()

This will:

  • result in null if the array does not contain Strings
  • result in null if the array is empty
  • result in the first String if the array contains a String