testivanivan
testivanivan

Reputation: 1514

Kotlin. Vararg how to filter null values

I have an API that has method which takes vararg of some object (fox example Param). I need to filter null params and not put it to vararg. Is it possible ?

I know there is a method in kotlin listOfNotNull but api accepts vararg(

This is example of calling API method (apiMethod(vararg params: Param)):

someFun() {
   apiMethod( 
      Param("first"),
      Param("second"),
      null // need to filter it
    )
}

P.S. I can't change apiMethod()

Upvotes: 0

Views: 559

Answers (3)

Tenfour04
Tenfour04

Reputation: 93629

If I understand your question correctly, you need to filter your arguments before passing them to the function since you cannot modify the function. To do this, you can filter to a List, and then convert that list to a typed array and pass it using the * spread operator:

fun someFun() {
   apiMethod( 
      *listOfNotNull(
          Param("first"),
          Param("second"),
          null // need to filter it
      ).toTypedArray()
    )
}

It's a shame you have to use toTypedArray(). IMO, it should be supported for all Iterables, since Lists are far more common than Arrays. This feature request has not had a lot of attention from JetBrains.

Upvotes: 3

Nikola Despotoski
Nikola Despotoski

Reputation: 50548

Your apiMethod() should fail either filter out nulls or just fail if provided list that contains null

fun apiMethod(a : Int, b : String, vararg params : List<Any?>){
   require(params.size == params.mapNotNull { it }.size) {
        "Params must not contain null values"
   }
   // or 
   val filtered = params.mapNotNull { it } 
  
}

Upvotes: 0

Michael Babozhko
Michael Babozhko

Reputation: 39

Try mapNotNull method

 val notNullArgs = args.mapNotNull { it }

If there will be any null it it will be filtered

Upvotes: 0

Related Questions