kotlin - Using a let to return if receiver is null for error case
问题描述
Kotlin 1.2.50
I have the following provided dependency that will create a MovieListItemDecorator and in the constructor it will pass a drawable. However, the getDrawable method can return a nullable:
i.e.
@Nullable
public static final Drawable getDrawable(@NonNull Context context, @DrawableRes int id)
I am thinking what can I do the case of the getDrawable returning a null value: I have specified 2 cases below. But if the getDrawable does return null I don't want to pass that in the constructor of the MovieItemDecorator()
1)
@MovieListScope
@Provides
fun provideMovieItemDecorator(context: Context): MovieItemDecorator {
var drawable: Drawable by Delegates.notNull()
ContextCompat.getDrawable(context, R.drawable.blue_border)?.let {
drawable = it
}
return MovieItemDecorator(drawable)
}
2)
@MovieListScope
@Provides
fun provideMovieItemDecorator(context: Context): MovieItemDecorator {
ContextCompat.getDrawable(context, R.drawable.blue_border)?.let {
return MovieItemDecorator(it)
} ?: {
return MovieItemDecorator(....) /* what to return here */
}
}
解决方案
很难理解你的问题,但我猜你最终想要一个 MovieDecorator。
如果此 MovieItemDecorator 需要一个可绘制参数,那么对于 null 的情况,您必须有一个可绘制(比如 ColorDrawable)
@MovieListScope
@Provides
fun provideMovieItemDecorator(context: Context) : MovieItemDecorator {
val drawable = ContextCompat.getDrawable(context, R.drawable.blue_border) ?: ColorDrawable()
return MovieItemDecorator(drawable as Drawable)
}
推荐阅读
- sml - 递归漂亮的打印表达式
- python - 递归列出数据模型中任意深度的所有对象?
- javascript - javascript(谷歌应用程序脚本)声明变量
- git - Git说所有提交都在一台计算机(Windows)上完成,而不是另一台(Mac)的网络驱动器?
- webhdfs - hdfs dfs -ls webhdfs:// 未列出所有文件
- php - changePSW 功能不起作用
- vba - 根据特定的内部颜色在单元格周围添加白色边框
- javascript - 获取对象文字字符串,周围有额外的字符串装饰
- pointers - 切片和指针的范围
- apache-spark - Spark结构化流替换列的值