为什么我们在Kotlin中具有名为componentN的函数 [英] Why do we have functions that named componentN in Kotlin

查看:858
本文介绍了为什么我们在Kotlin中具有名为componentN的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚查看了Kotlin

I've just looked at Kotlin standard library and found some strange extension-functions called componentN where N is index from 1 to 5.

有适用于所有类型基本体的函数.例如:

There are functions for all types of primitives. For example:

/**
* Returns 1st *element* from the collection.
*/
@kotlin.internal.InlineOnly
public inline operator fun IntArray.component1(): Int {
    return get(0)
}

对我来说看起来很奇怪.我对开发人员的动机感兴趣.呼叫array.component1()而不是array[0]更好吗?

It looks curiously for me. I'm interested in developers motives. Is it better to call array.component1() instead of array[0] ?

推荐答案

Kotlin具有许多功能,可按约定启用特定功能.您可以使用operator关键字来识别它们.示例包括委托,运算符重载,索引运算符以及解构声明.

Kotlin has many functions enabling particular features by convention. You can identify those by the use of the operator keyword. Examples are delegates, operator overload, index operator and also destructuring declarations.

函数componentX允许在特定类上使用解构.您必须提供这些功能,以便能够将该类的实例分解为它的 components .很高兴知道data类在默认情况下为其中的每个属性提供了这些属性.

The functions componentX allow destructuring to be used on a particular class. You have to provide these functions in order to be able to destructure instances of that class into its components. It’s good to know that data classes provide these for each of there properties by default.

获取数据类Person:

data class Person(val name: String, val age: Int)

它将为每个属性提供一个componentX函数,以便您可以按如下所示对其进行解构:

It will provide a componentX function for each property so that you can destructure it like here:

val p = Person("Paul", 43)
println("First component: ${p.component1()} and second component: ${p.component2()}")
val (n,a) =  p
println("Descructured: $n and $a")
//First component: Paul and second component: 43
//Descructured: Paul and 43

也请参见我在另一个线程中给出的答案:

Also see this answer I gave in another thread:

https://stackoverflow.com/a/46207340/8073652

这篇关于为什么我们在Kotlin中具有名为componentN的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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