MongoDB getList("field-name", Double::class.java); produces ClassCastException in Kotlin

Viewed 408

I'm trying to retrieve a field containing an array of Double from MongoDB, but I'm receiving a

ClassCastException: List element cannot be cast to double.

The class is written in Kotlin, and the part of the code that produces the exception is:

val coordinates = doc.getList(FIELD_COORDINATES, Double::class.java)

This works:

val coordinates = doc.get(FIELD_COORDINATES) as List<Double>

And the equivalent code in Java works too:

final List<Double> coordinates = doc.getList(FIELD_COORDINATES, Double.class);

enter image description here

Please let me know if this is a bug in Kotlin or there's a mistake in my code.

2 Answers

The equivalent of Double::class.java in Java is double.class, not Double.class. That would be written as java.lang.Double::class.java in Kotlin, or Double::class.javaObjectType.

The answer of Alexey is correct. Here is an example how it should look like:

val coordinates = doc.getList("coordinates", Double::class.javaObjectType)

Notice the use of the Java ObjectType of Double.

Related