gpt4 book ai didi

kotlin - Kotlin-循环中的销毁不起作用-无法访问var

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

一些background:

val (name, age) = person 

此语法称为解构声明。它同时创建多个变量(更正,创建多个值)。

解构声明也可以在for循环中使用:当您说:
for ((a, b) in collection) { ... }

让我们看看我有一个列表项:
    @Parcelize
data class MyModel(
var name: String = "",
var is_locked: Boolean = true,
var is_one_size: Boolean = false,
) : Parcelable

现在我已经获得了“MyModel”类的列表,并且我试图像这样遍历它们:
private fun initMyModelList(model: MutableList<MyModel>) {
//i want to access is_locked from here with destruction but i cant ? IDE telling me the type is an int but its clearly defined as a Boolean
for((is_locked) in model){
//what i want to do in here is access the is_locked var of the model list and change all of them in a loop. im trying to use Destructuring in loop as a conveience. why is it not working ?
//how can i make the call signature look like this--- > is_locked = true instad of model.is_locked =true
}
}

我要做的就是能够在循环内调用is_locked = true而不是model.is_locked = true。如何才能做到这一点 ?

最佳答案

This syntax is called a destructuring declaration. It creates multiple variables at at the same time.


它不创建多个变量,而是捕获多个值。您正在使用值而不是引用,正如您的资料进一步说明的那样:

A destructuring declaration is compiled down to the following code:

val name = person.component1()
val age = person.component2()

最接近您想要的是此自定义扩展功能:
inline fun <E> Iterable<E>.withEach(block: E.() -> Unit) {
forEach {
it.block()
}
}
像这样使用:
model.withEach {
is_locked = true
}
在问强制性问题“为什么stdlib中不包含此内容?”之前,考虑到功能样式编程通常是关于转换不可变类型的。基本上,我在这里所做的是鼓励养成不良习惯。

关于kotlin - Kotlin-循环中的销毁不起作用-无法访问var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48396720/

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