Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
Kotlin compiler not warning about potential null pointer exception

I have this simple kotlin snipped that tries to map list elements to strings like this:

sealed class MySealedClass

class MyClass1 : MySealedClass()

class MyClass2 : MySealedClass()

fun doTheMapThing(elements: List<MySealedClass>): List<String> {
    return elements.flatMap {
        when (it) {
            is MyClass1 -> listOf("Yeah")
            is MyClass2 -> null
        }
    }
}

In the flatMap, the when either maps to a list or to null, so the effective return type of the when is List<String>?. I was a bit surprised to see this compiling without any issues. Shouldn't the kotlin compiler warn about this? When I extract the when to a function, I get a proper compiler error. Am I missing something here or could this be a bug?

Using kotlin 1.5.31

over 4 years ago · Hanz Gallego
1 Respostas
Responde à pergunta

0

Just for completeness: It was a bug. The fix will be released with Kotlin 1.7.0. More details on that can be found here: https://youtrack.jetbrains.com/issue/KT-49658

If you're interested in even more details, you can find the actual fix here: https://github.com/JetBrains/kotlin/commit/37d163d417bfe8ecd2e4baea3e5651906c96e150

A nice thing is that our example actually made it into the test code for kotlin:

fun doTheMapThing1(elements: List<CharSequence>): List<String> {
    return elements.flatMap {
        <!TYPE_MISMATCH_WARNING!>when (it) { // NullPointerException
            is String -> listOf("Yeah")
            else -> null
        }<!>
    }
}
over 4 years ago · Hanz Gallego Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda