Erik Bender
11/11/2021, 8:14 AMByteArray
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?Ulrik Rasmussen
11/11/2021, 10:50 AM@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.