[英]How to restrict access to the outer Lambda method from the inner Lambda when using the Lambda of the Kotlin extension function?
我在 Jetpack Compose 中模仿 LazyDsl 来实现自定义首选项布局。
这是我的代码:
@Composable
fun PreferenceContainer(
/* ... */,
content: PreferenceScope.() -> Unit
) {
LazyColumn(
/* ... */,
content = PreferenceScope(context).apply(content).getLazyListScope()
)
}
class PreferenceScope(private val context: Context) {
private val itemList = mutableListOf<@Composable () -> Unit>()
fun getLazyListScope(): LazyListScope.() -> Unit = {
items(itemList) { it() }
}
fun category(title: String, items: PreferenceCategoryScope.() -> Unit) {
/* ... */
}
}
class PreferenceCategoryScope(private val itemList: MutableList<@Composable () -> Unit>, context: Context) {
private val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
fun editPreference( /* ... */ ) {
/* ... */
}
}
可以这样调用:
PreferenceContainer( /* ... */ ) {
category( /* ... */ ) {
editPreference( /* ... */ )
}
}
但它也可以这样使用:
PreferenceContainer( /* ... */ ) {
category( /* ... */ ) {
category( /* ... */ ) { } //This is not what I want: category() is called in category()
}
}
因此,这个问题可以体现为:如何让category()
无法被拉姆达参数称为category()
如果有人知道,我将不胜感激,谢谢!
在评论中提醒我后,我找到了答案。
代码可以这样修改:
@DslMarker
annotation class PreferenceDsl
@Composable
fun PreferenceContainer(
/* ... */,
content: PreferenceScope.() -> Unit
) {
LazyColumn(
/* ... */,
content = PreferenceScope(context).apply(content).getLazyListScope()
)
}
@PreferenceDsl
class PreferenceScope(private val context: Context) {
private val itemList = mutableListOf<@Composable () -> Unit>()
fun getLazyListScope(): LazyListScope.() -> Unit = {
items(itemList) { it() }
}
fun category(title: String, items: PreferenceCategoryScope.() -> Unit) {
/* ... */
}
}
@PreferenceDsl
class PreferenceCategoryScope(private val itemList: MutableList<@Composable () -> Unit>, context: Context) {
private val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
fun editPreference( /* ... */ ) {
/* ... */
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.