Kotlin for deconstruction, quadruple, quintuple, etc

I am looking for a clean way to create destructible objects online kotlin. Pair and kotlin Triple covers many use cases, but sometimes more objects need to be passed

An example use case is the zip function of Rx, in which the results of several I / O calls need to be mapped to another object:

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

I want to find out what happens in the "some kotlin magic" section If there are only three repositories, that is

Triple(objectA,objectsC)

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

Solution

basic

Let's see how deconstruction works:

Kotlin defines a convention for this, that is, the componentx () operator function, which is an example of the Convention principle used in kotlin in many places The compiler uses these componentx () functions to initialize variables in the deconstruction declaration

For example, in pair < A, b > These functions are as follows:

operator fun component1(): A = first 

operator fun component2(): B = second

As you can see, these are the functions specially handled by operators These componentx () functions can be provided by developers and automatically generate data classes by the compiler For the same data class btw

answer

Therefore, you can continue to use data classes as long as you need more than three data

For example, a multicomponent class is defined as follows:

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

Will be compiled into a class with functions component1(), component2(),..., component6(), and can be used in the deconstruction declaration:

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

For more details on kotlin conventions and deconstructions, see this blog post

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>