简体   繁体   English

Kotlin。 Vararg 如何过滤 null 值

[英]Kotlin. Vararg how to filter null values

I have an API that has method which takes vararg of some object (fox example Param).我有一个 API 具有采用一些 object 的可变参数的方法(狐狸示例参数)。 I need to filter null params and not put it to vararg.我需要过滤 null 参数,而不是将其放入可变参数。 Is it possible?可能吗?

I know there is a method in kotlin listOfNotNull but api accepts vararg (我知道 kotlin listOfNotNull中有一种方法,但 api 接受vararg参数(

This is example of calling API method (apiMethod(vararg params: Param)):这是调用 API 方法的示例(apiMethod(vararg params: Param)):

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

PS I can't change apiMethod() PS 我不能改变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.如果我正确理解您的问题,您需要先过滤您的 arguments,然后再将它们传递给 function,因为您无法修改 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() .很遗憾您必须使用toTypedArray() IMO, it should be supported for all Iterables, since Lists are far more common than Arrays. IMO,所有Iterables都应该支持它,因为列表比Arrays更常见。 This feature request has not had a lot of attention from JetBrains.功能请求并未引起 JetBrains 的太多关注。

Your apiMethod() should fail either filter out nulls or just fail if provided list that contains null如果提供的列表包含apiMethod()

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

Try mapNotNull method试试 mapNotNull 方法

 val notNullArgs = args.mapNotNull { it }

If there will be any null it it will be filtered如果有任何 null it被过滤

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM