Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap errors - containsKey, get

Tags:

kotlin

Can anyone shed some light?

Problem code:

protected var table = HashMap<Class<*>, Double>()

if (table.containsKey(object)) {
    value = table.get(object)
} 

containsKey(K):Boolean is deprecated. Map and Key have incompatible types. upcast to Any? if you're sure

so I changed it to this:

if (table.containsKey(object as Any?)

which fixes the error, but is this what I should have done to fix it? or is there a better way?

also .get(object) has an error:

Type inference failed. required: kotlin.Double found kotlin.Double?

same error message for this too:

val c = someObject.javaClass // pre j2k code: final Class<? extends SomeClass> c = someObject.getClass();
weight = weightingTable[c] <-- error here

I don't know what to do here

like image 373
ycomp Avatar asked Jul 09 '26 23:07

ycomp


2 Answers

The containsKey call is reported as an error because the type of the argument you pass to it does not match the type of the map key. Your map contains classes as keys, and you're trying to pass an object instance to it. Changing this to object as Any? is not a useful fix, because this call will compile but will always return false. What you need to do instead is to use object.javaClass to get the class of the object.

The weightingTable[c] call is reported as an error because the map does not necessarily contain a value for the key you're passing to it, so the result of the [] operation is nullable. You cannot assign a nullable value to a non-null variable without somehow handling the null case (using a check, an explicit non-null cast or some other option covered in the documentation).

like image 185
yole Avatar answered Jul 14 '26 19:07

yole


When doing:

myHashMap.get(object)

and getting:

Type inference failed. required: kotlin.Double found kotlin.Double?

even when you already checked with containsKey. You can solve it by using:

myHashMap.getOrElse(key) { defaultValue }
like image 20
Lucas Avatar answered Jul 14 '26 17:07

Lucas