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

323
Visualizações
Filtering out non null values from a collection in kotlin

Take a look at this kotlin one liner:

val nonNullArr : List<NonNullType> = nullArray.filter {it != null}

The compiler gives a type error at this line, saying that a list of nullables can't be assigned to a list of non-nulls. But the filter conditional makes sure that the list will only contain non null values. Is there something similar to !! operator that I can use in this situation to make this code compile?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

It seems logical to assume that the compiler would take into account the predicate

it != null

and infer the type as

List<NonNullType>

but it does not.
There are 2 solutions:

val nonNullList: List<NonNullType>  = nullableArray.filterNotNull()

or

val nonNullList: List<NonNullType>  = nullableArray.mapNotNull { it }
over 4 years ago · Santiago Trujillo Relatório

0

As far as I know, you cannot convert nullable types into nonNull types by just verifying that they are not null. To achieve what you want, you need to manually map nullable values to non-null type by simply creating NonNull type object. For this you can use map extension function.

val nullableArray: Array<String?> = arrayOf("abc", "xyz", null, "efg")

val nonNullList: List<String> = nullableArray.filter { it != null }.map {
    it.toString()
}

Or you can use filterNotNull() method as @forpas suggested in comments

val nonNullList: List<String>  = nullableArray.filterNotNull()

Hope it helps you!

over 4 years ago · Santiago Trujillo Relatório

0

You can't assign a nullable type to a non-nullable type of value. The type-matching maybe works when you assign a value, not after filter operation called.

// the type-matching works before `.filter` is called
val nonNullArr : List<NonNullType> = nullArray//.filter {it != null} 

instead, if you want to do this without an error or without concerning the type. Remove the type from the val, so it goes like this

val nonNullArr = nullArray.filter {it != null} 

Hope it helps

over 4 years ago · Santiago Trujillo 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