且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将数组映射到对象kotlin列表

更新时间:2023-02-10 08:52:16

尝试或者如果您更喜欢它:

val list = a.zip(b)
            .map { (a, b) -> SomeClass(a, b) }

请注意,如果两个数组的大小均不同,则其他值将被忽略.还要注意,这将创建中间Pair(这是zip的默认转换函数).尽管我更喜欢显式的map,但有关重载方法的@hotkeys解决方案更合适(您可以保留隐藏的Pair -transformation):

Note that if both arrays differ in size, the additional values are ignored. Note also that this will create intermediate Pairs (which is the default transformation function of zip). Even though I like the explicit map more, @hotkeys solution regarding the overloaded method is more appropriate (you spare that hidden Pair-transformation):

val list = a.zip(b) { a, b -> SomeClass(a, b) }

当使用引用代替时,重载方法可能发光的地方:

And where the overloaded method probably shines, is when using references instead:

a.zip(b, ::SomeClass)

只要您有一个与压缩参数匹配的构造函数,并且在Pair范围内无法使用(还可以吗?),这将起作用.

Which will work as long as you have a constructor matching the zipped arguments and doesn't work out of the box for the Pair (yet?).