简化包含关键Android Studio的捆绑包的使用

简化包含关键Android Studio的捆绑包的使用,android,kotlin,Android,Kotlin,我想检查捆绑包是否具有指定的密钥 有没有现代的方法用kotlin来检查它 现在我正在使用 if(bundle.containsKey(Extras.PRODUCT){ bundle.getParcelable<Product>(Extras.PRODUCT)?.let{ mpresenter.mProduct = it } } if(bundle.containsKey(Extras.ANIMAL){ bundle

我想检查捆绑包是否具有指定的密钥

有没有现代的方法用kotlin来检查它

现在我正在使用

    if(bundle.containsKey(Extras.PRODUCT){
    bundle.getParcelable<Product>(Extras.PRODUCT)?.let{
    mpresenter.mProduct = it
     } 
    }
    
    if(bundle.containsKey(Extras.ANIMAL){
    bundle.getParcelable<ANIMAL>(Extras.ANIMAL)?.let{
    mpresenter.mAnimal = it
      }
    }
if(bundle.containsKey(附加产品){
捆绑。获取包裹(附加产品)?。让{
mpresenter.mpproduct=it
} 
}
if(包裹容器)(额外动物){
包裹。带包裹(额外的动物)?。让{
mpresenter.mAnimal=it
}
}
……等等

如果我只检查附加值的一个值就可以了。但是如果presenter中有10个或更多变量,该怎么办呢?对于我的情况,有没有更简单的解决方案?

现在推荐使用来导航和传递数据

相关代码实验室

导航组件有一个称为safe args的Gradle插件 生成简单的对象和生成器类,用于对 为目标和操作指定的参数

Safe args允许您在传递值时摆脱这样的代码 目的地之间:

val username=arguments?.getString(“usernameKey”)
而, 用生成setter和getter的代码替换它

val username=args.username


你可以做一些扩展函数,比如

fun <T : Parcelable?> Bundle.tryGetParcelable(key: String): T? =
    // getParcelable would return null anyway, but this is a general example
    if (containsKey(key)) getParcelable<T>(key) else null

bundle.tryGetParcelable<Product>(Extras.PRODUCT)?.let { mPresenter.mProduct = it }
但是您可能希望将属性改为接收者,因此它的读取方式更像通常的
thing=which

fun <T : Parcelable> KMutableProperty0<T>.tryAssign(bundle: Bundle, key: String) {
    bundle.tryGetParcelable<T>(key)?.let { set(it) } // or run(::set)
}

mPresenter::mProduct.tryAssign<Product>(bundle, Extras.PRODUCT)

我的意思是,这开始变得有点紧张,但是如果你有很多东西要分配,那么像这样干净地排序可能是值得的?无论如何要尝试一些东西!

你能不能制作一个大的可包裹对象,它将包含你需要的所有字段,而不是分配关键点并重新映射所有内容?哇……真是太神奇了,扩展函数真的非常有帮助。@cactustictacs感谢您逐案提供的所有答案,真的很有帮助。很遗憾,我现在的公司仍在使用旧的方式,也许不久的将来会使用它的全部功能。一些功能已经实现了导航,我也在使用它来传递bundle/args safeargs。谢谢您的回复。
fun <T : Parcelable> KMutableProperty0<T>.tryAssign(bundle: Bundle, key: String) {
    bundle.tryGetParcelable<T>(key)?.let { set(it) } // or run(::set)
}

mPresenter::mProduct.tryAssign<Product>(bundle, Extras.PRODUCT)
// Not using this here but it's the same getter signature, (Bundle, String) -> T?
// Note that because we're going to be passing references to these functions, we can't 
// define them as extension functions in the same file - so the Bundle is a parameter now
fun tryGetString(bundle: Bundle, key: String): String? {
    return bundle.getString(key)
}

// Now we're passing in the getter function we want to use, which returns a T?
// T doesn't have a Parcelable upper bound anymore
fun <T> KMutableProperty0<T>.tryAssign(bundle: Bundle, key: String, tryGet: (Bundle, String) -> T?) {
    tryGet(bundle, key)?.run(::set)
}

// you won't need the type in diamond brackets, it's just for illustration
mPresenter::mProduct.tryAssign<Product>(bundle, Extras.PRODUCT, ::tryGetParcelable)