简体   繁体   English

空对象模式是否有安全的“无 id”@StringRes 或 @DrawableRes 值?

[英]Is there a safe "no id" @StringRes or @DrawableRes value for a null object pattern?

Suppose I wanted to implement a null object pattern of a model so as to guarantee an object that will do nothing, without requiring null checks on nullable fields.假设我想实现模型的空对象模式,以保证对象什么都不做,而不需要对可空字段进行空检查。

interface Model(
    val textId: Int,
    val imageId: Int,
    ...
)

data class ModelImpl(
    @StringRes val textId: Int,
    @DrawableRes val imageId: Int,
    ...
) : Model

data class NullModel(
    @StringRes val textId: Int = StringRes.None, // some value representing no value ?
    @DrawableRes val imageId: Int = DrawableRes.None,
    ...
) : Model

Is there any resource id number for strings or drawables, that could be passed to stringResource(id = model.textId) or painterResource(id = model.imageId) which would result in an empty string or a 'placeholder no image' without trigging an error?字符串或可绘制对象是否有任何资源 ID 号,可以传递给stringResource(id = model.textId)painterResource(id = model.imageId) ,这将导致空字符串或“占位符无图像”而不触发错误?

Alternatively I could, of course, make an empty string resource and blank image resource to refer to myself but I would also question if, in the world of clean architecture and/or idiomatic Kotlin code, this is even a good practise in the first place?或者,我当然可以创建一个空字符串资源和空白图像资源来引用我自己,但我也会质疑,在干净的架构和/或惯用的 Kotlin 代码的世界中,这是否是一个好的实践?

Edit: I noticed that in the Android Docs, the parameter type of compose's resource function's id is Int?编辑:我注意到在 Android Docs 中,compose 的资源函数 id 的参数类型是Int? , but contrary to this documentation, in the Compose version I am using, 1.2.0-alpha04, these id parameters are not nullable types. ,但与本文档相反,在我使用的 Compose 版本 1.2.0-alpha04 中,这些 id 参数不是可为空的类型。 I also ask this question for the Resources.getString() etc. equivalents which are also not nullable.我还针对同样不可为空的 Resources.getString() 等等价物问这个问题。 https://developer.android.com/reference/kotlin/androidx/compose/ui/res/package-summary https://developer.android.com/reference/kotlin/androidx/compose/ui/res/package-summary

I couldn't find any elegant solution to this either.我也找不到任何优雅的解决方案。 What I ended up doing is the following:我最终做的是以下内容:

state.emailError?.let { stringResource(it) }.orEmpty()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM