Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

251
Vistas
ClassCastException in Kotlin even though the conditional statement checks that it's of right type

I'm burning cycles trying to understand why I'm getting a cast error when I know for a fact that it's a string.

Anyone else seen this in Kotlin? (it fails at the second to last line).

val stringValue =
    if (attributesMap[it] !is String) { // same as !(obj is String)
        gson.toJson(attributesMap[it])
    } else if (attributesMap[it] == null) {
        ""
    } else {
        if (attributesMap[it] is String)
            logger.info("it's a string wth...${attributesMap[it]}")
            
        attributesMap[it] // <--- The stacktrace shows this line as the culprit, and the above "it's a string line" is printed out as well
    }

Here's the error:

java.lang.ClassCastException: class java.util.ArrayList cannot be cast to class java.lang.String (java.util.ArrayList and java.lang.String are in module java.base of loader 'bootstrap')

Updated 1: this started happening after I upgraded from Kotlin 1.4.10 to 1.5.30. Also the input that it fails on is a string that looks like an array: ["item1", "item2"]

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

I guess the problem is that attributesMap[it] is not a property itself. It's actually a function call attributesMap.get(it). That's why compiler is not able to smart cast it.

Also, I am not sure of your order of if statements. If attributesMap[it] !is String is false, attributesMap[it] == null will definitely be false.

Try this code, see if it works for you.

val value = attributes[it] // Store the value beforehand
val stringValue =
    if(value == null)
        ""
    else if(value is String)
        value
    else
        gson.toJson(value)

You can also replace this if-else ladder with a when statement.

Playground

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda