https://kotlinlang.org logo
Title
e

Erik Bender

11/11/2021, 8:14 AM
Hi 🙂 I have this function to deserialize generic lists from
ByteArray
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

Ulrik Rasmussen

11/11/2021, 10:50 AM
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.