有什么方法可以避免!用Kotlin代码编写?

时间:2020-03-29 19:20:28

标签: android kotlin

我正在审查使用Lottie的一段代码 这是代码

class ProgressToProgress(context: Context) : LottieIconTransition(
LottieCompositionFactory.fromRawResSync(
    context, R.raw.downloadprogress).value!!)

其中

  @Nullable public V getValue() {
return value;}

getValue()方法来自Lottie库,因此我无法对其进行任何控制。 我不喜欢那里!在上面,有趣的是,LottieIconTransition的构造函数看起来像这样,它具有默认的构造函数param

class LottieIconTransition(private val lottieComposition: LottieComposition = LottieComposition())

我想知道什么是避免发生的最佳做法!在代码中?

1 个答案:

答案 0 :(得分:2)

这就是我使用工厂方法的意思。

class ProgressToProgress {

    constructor() : super()
    constructor(res: LottieResult<LottieComposition>) : super(res)

    companion object {
        @JvmStatic
        fun create(context: Context): ProgressToProgress {
            val res = LottieCompositionFactory.fromRawResSync(
                    context, R.raw.downloadprogress).value
            return if (res == null) {
                ProgressToProgress()
            } else {
                ProgressToProgress(res)
            }
        }
    }
}

但是这很麻烦,您可能要自己指定默认值,即:

class ProgressToProgress(context: Context) : LottieIconTransition(
        LottieCompositionFactory.fromRawResSync(
            context, R.raw.downloadprogress).value ?: <respecify super default parameter value>)