Reputation: 9306
I do not want to suppress warning I actually want to check the cast and remove unwanted types if it happens. Trying to figure out best way but all examples are for lists not Maps. This function is used by many classes and it can get data I don't want. I only want ones that are serializable in this instance from inside this class.
class Controller(private val manager: Manager) {
override fun onStatusUpdate(update: Map<String, *>) {
// This is where I want to check is the value Serializable type
manager.onStatusUpdate(update as Map<String, Serializable>)
}
}
class Manager {
fun onStatusUpdate(dataMap: Map<String, Serializable>) {
dataMap.doSomething()....
}
}
Upvotes: 1
Views: 1473
Reputation: 7902
manager.onStatusUpdate(update.filterValues { it is Serializable }.mapValues { it.value as Serializable })
filterValues
will remove all values of unwanted types, mapValues
will change the type from Map<String, Any?>
to Map<String, Serializable>
, making compiler happy.
Upvotes: 1
Reputation: 18617
This isn't possible, I'm afraid.
That's a result of type erasure. Due to the way generics were added to Java back in JDK 1.5, type parameters are not included in the compiled bytecode. This means that both a Map<String, Serializable>
and a Map<Int, List<Pair<String, Float>>
would be compiled (after inserting all the necessary casts) down to a simple Map
, with no information about the key or value types.
So at runtime, they're the same, and there's no way to distinguish them. (You could look at the contents, and discount some possible types; but that wouldn't help you in general, because Map<Any?, Any?>
would always be a possibility.)
That's why the compiler warns you: it's not just that you haven't checked the type: it's that you can't check the type.
(The only way to make an unchecked cast safely would be to have some other way to know the type: for example, if you also stored the class names or Class objects separately. Otherwise, there's always the risk of a ClassCastException, which you'd do well to allow for in some way.)
In your case, one workaround might be to check the contents of the map; if every value is Serializable
, that might give the required behaviour, without needed to check the type of the map itself.
Upvotes: 3