Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

316
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!