将 Kotlin 数组转换为 Java 可变参数 [英] Convert Kotlin Array to Java varargs

查看:41
本文介绍了将 Kotlin 数组转换为 Java 可变参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将我的 Kotlin Array 转换为可变参数 Java String[]?

How can I convert my Kotlin Array to a varargs Java String[]?

val angularRoutings = 
    arrayOf<String>("/language", "/home")

// this doesn't work        
web.ignoring().antMatchers(angularRoutings)

如何将 ArrayList 传递给可变参数方法参数?

推荐答案

展开运算符,用 * 表示.
展开运算符放在数组参数的前面:

There’s the spread operator which is denoted by *.
The spread operator is placed in front of the array argument:

antMatchers(*angularRoutings)

有关详细信息,请参阅文档:

For further information, see the documentation:

当我们调用一个 vararg 函数时,我们可以一个接一个地传递参数,例如asList(1, 2, 3),或者,如果我们已经有一个数组并且想要将它的内容传递给函数,我们使用扩展运算符(用 * 前缀数组代码>):

When we call a vararg-function, we can pass arguments one-by-one, e.g. asList(1, 2, 3), or, if we already have an array and want to pass its contents to the function, we use the spread operator (prefix the array with *):

请注意,展开运算符仅针对数组定义,不能直接用于列表.处理列表时,使用例如toTypedArray() 将其转换为数组:

Please note that the spread operator is only defined for arrays, and cannot be used on a list directly. When dealing with a list, use e.g.toTypedArray() to transform it to an array:

 *list.toTypedArray()

这篇关于将 Kotlin 数组转换为 Java 可变参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆