Kotlin四重,五重等用于解构 [英] Kotlin quadruple, quintuple, etc. for destructuring

查看:125
本文介绍了Kotlin四重,五重等用于解构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种干净的方法来在线创建可破坏的对象. kotlin.Pairkotlin.Triple涵盖了许多用例,但有时需要传递更多的对象.

I am looking for a clean way to create destructurable objects in-line. kotlin.Pair and kotlin.Triple cover a lot of use cases, but sometimes there are more objects that are needed to be passed.

一个简单的用例是RX的zip函数,其中几个I/O调用的结果需要映射到另一个对象中:

One sample use case is RX's zip function, where the results of several I/O calls need to be mapped into another object:

Single
    .zip(repositoryA.loadData(someId),
         repositoryB.loadData(someId),
         repositoryC.loadAll(),
         repositoryD.loadAll()),
         { objectA, objectB, objectsC, objectsD -> /*some Kotlin magic*/ }
    )
    .map { (objectA, objectB, objectsC, objectsD) -> /*do the mapping*/ }

我正在尝试弄清楚科特林魔咒"部分的内容.如果只有3个存储库,那么它将是

I am trying to figure out what would go in the "some Kotlin magic" part. If there were only 3 repositories, it would be

Triple(objectA, objectB, objectsC)

我是否需要为此创建一个新的数据类,对于任何n元组情况,还是还有另一种方法?

Do I need to create a new data class for this, and for any n-tuple case, or is there another way?

推荐答案

基础

让我们看看解构的工作原理:

Kotlin为此定义了一个约定,即componentX() operator函数是Kotlin在许多地方使用的约定原理的示例.这些componentX()函数由编译器用于在解构声明中初始化变量.

Kotlin defines a convention for this, i.e. componentX() operator functions are an example of the principle of conventions used in Kotlin in many places. These componentX() functions are used by the compiler for the initialization of variables in destructuring declarations.

例如,在Pair<A,B>中,这些函数如下所示:

For example in Pair<A,B> these functions look as follows:

operator fun component1(): A = first 

operator fun component2(): B = second

如您所见,这些是专门处理的函数 operators . 这些componentX()函数可以由开发人员提供,并由编译器针对data类自动生成. Pair也是data类btw.

As you can see these are operators, specially handled functions. These componentX() functions can be provided by the developer and will automatically be produced by the compiler for data classes. Pair also is such a data class btw.

因此,只要您需要除Triple以外的其他任何内容,就继续使用data类.

Thus, just go ahead and use data classes whenever you need more than a Triple.

例如,定义为以下类的MultiComponent:

For example, a class MultiComponent defined as this:

data class MultiComponent(val x: Int, val y: Int, val z: Int, val a: Int, val b: Int, val c: Int)

将被编译为具有函数component1()component2(),...,component6()的类,并可用于解构声明:

will be compiled to a class with functions component1(), component2(), ..., component6() and can be used in destructuring declarations:

val (q, w, e, r, t, z) = MultiComponent(1, 2, 3, 4, 5, 6)

这篇关于Kotlin四重,五重等用于解构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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