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