Hi :slightly_smiling_face: I have this function to...
# getting-started
e
Hi ­čÖé I have this function to deserialize generic lists from
ByteArray
Copy code
fun mapBytesToList(arr: ByteArray): List<T> {
  if (arr.isEmpty()) {
    return emptyList()
  }
  val bais = ByteArrayInputStream(arr)
  var ois: ObjectInputStream? = null
  return try {
    ois = ObjectInputStream(bais)
    ois.readObject() as List<T>
  } catch (e: Exception) {
    emptyList()
  } finally {
    try {
      ois?.close()
    } catch (e: Throwable) {
    }
  }
}
I get a
UNCHECKED_CAST
warning at
ois.readObject() as List<T>
. Do you have a hint on how to improve this function?
u
Regarding the cast, I don't think you can improve it beyond suppressing the warning using
@Suppress
. It is a fundamental limitation on the JVM that you cannot safely cast to a generic type, due to type erasure. Finally, consider using
ObjectInputStream(ByteArrayInputStream(arr)).use { ois -> ... }
to save the cleanup code.