gpt4 book ai didi

kotlin - 如何在Kotlin中破坏构造函数

转载 作者:行者123 更新时间:2023-12-02 13:06:39 26 4
gpt4 key购买 nike

如何以这种方式在Kotlin中编写类,以便在初始化时可以销毁它,例如:

val (set, list, map) = CollectionsGenerator(arg1, arg2)

最佳答案

为了解构对象,您需要在其上定义以下形式的方法(其中X是从1开始的数字,并且返回类型可以是您希望返回的任何值):

operator fun componentX(): Any {}

要执行与问题类似的操作,可以将构造类所使用的参数保存到属性中,然后 component方法可以使用这些属性:
class SetAndListMaker(val i: Int, val s: String) {

operator fun component1() = setOf(i, s)

operator fun component2() = listOf(i, s)

}

fun main(args: Array<String>) {
val (set, list) = SetAndListMaker(25, "dog")
}

当然,此主要功能与此功能没有什么不同:
fun main(args: Array<String>) {
val setAndListMaker = SetAndListMaker(25, "dog")
val (set, list) = setAndListMaker
}

And here's the official documentation about destructuring declarations.

关于kotlin - 如何在Kotlin中破坏构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43051196/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com