Home > Back-end >  Kotlin. Vararg how to filter null values
Kotlin. Vararg how to filter null values

Time:09-15

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()

CodePudding user response:

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.

CodePudding user response:

Try mapNotNull method

 val notNullArgs = args.mapNotNull { it }

If there will be any null it it will be filtered

CodePudding user response:

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 } 
  
}
  • Related