0

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

testivanivan
  • 967
  • 13
  • 36
  • You can pass a `List` to a varargs. See https://stackoverflow.com/q/51161558/5133585 – Sweeper Sep 15 '22 at 09:12
  • Does this answer your question? [Kotlin convert List to vararg](https://stackoverflow.com/questions/51161558/kotlin-convert-list-to-vararg) – Sweeper Sep 15 '22 at 09:13

3 Answers3

3

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.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154
0

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 } 
  
}
Nikola Despotoski
  • 49,966
  • 15
  • 119
  • 148
0

Try mapNotNull method

 val notNullArgs = args.mapNotNull { it }

If there will be any null it it will be filtered