Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - object type check against HashMap<String, String> shows warning

Tags:

casting

kotlin

I'm trying to check Serializable type before casting it to HashMap<String, String>. But it gives following warning;

Cannot check for instance of erased type: kotlin.collections.HashMap /* = java.util.HashMap */

Is there a way to check if Serializable is type of HashMap<String, String> then safe cast it?

params = if (it.getSerializable(ARG_PARAMS) is HashMap<String, String>) {
             it.getSerializable(ARG_PARAMS) as HashMap<String, String>
         } else null
like image 285
Farid Avatar asked Mar 03 '23 14:03

Farid


1 Answers

Actually, you cannot check that your object has type HashMap<String, String> because type parameters are erased in runtime. I would like to suggest you just use a safe cast:

params = arguments?.getSerializable(ARG_PARAMS) as? HashMap<String, String>

Important:

It might be not clear but my code doesn't check that argument really has type HashMap<String, String>. You can pass HashMap<String, Int> and in some case, you'll get an error. In my snippet you just say to the compiler: "I know that there will be HashMap<String, String>. Just give it to me". params will be null only when there is no argument or its type differs from HashMap.

like image 55
Andrei Tanana Avatar answered Apr 26 '23 16:04

Andrei Tanana