首页 > 解决方案 > 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 */
        }
    }

标签: kotlin

解决方案


很难理解你的问题,但我猜你最终想要一个 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)
    }

推荐阅读