Kotlin 在我的情况下,减少IF的数量

Kotlin 在我的情况下,减少IF的数量,kotlin,Kotlin,如果我的方法是这样的,我有太多: if (myObject?.name !=null) first.text = myObject.name.bigThing if (myObject?.age !=null) second.text = myObject.age.bigThing if (myObject?.surname !=null) third.text = myObject.surname.bigThing String extractBigThing(Big big){

如果我的方法是这样的,我有太多:

if (myObject?.name !=null)
first.text = myObject.name.bigThing

if (myObject?.age !=null)
second.text = myObject.age.bigThing

if (myObject?.surname !=null)
third.text = myObject.surname.bigThing
String extractBigThing(Big big){
    if(big != null) return big. GetBigThing() ;

    return null;
} 
还有20多个

如何缩短代码


年龄/姓氏/姓名
是用
id:Int
bigThing:String
键入我自己的类
Big
,如果您喜欢,可以这样更改它们:

myObject?.name?.run { first.text = this.bigThing }
一个选择是

fun updateText(x: WhateverTheTypeOfFirstSecondEtcIs, y: Big?) {
    if (y != null) { x.text = y.bigThing }
}

updateText(first, myObject?.name)
updateText(second, myObject?.age)
updateText(third, myObject?.surname)
一种方法可以是:

myObject?.age?.let { second.text = it.bigThing }
如果将值放入
文本视图中

first.text = myObject?.age?.bigThing

我不知道kotlin中的确切语法,但是我希望能够创建一个类似这样的方法:

if (myObject?.name !=null)
first.text = myObject.name.bigThing

if (myObject?.age !=null)
second.text = myObject.age.bigThing

if (myObject?.surname !=null)
third.text = myObject.surname.bigThing
String extractBigThing(Big big){
    if(big != null) return big. GetBigThing() ;

    return null;
} 
我们可以这样称呼它:

first.text = extractBigThing(myObject.name);
基本思想是将可重用功能提取到可重用代码中,然后对这些功能进行单元测试以提高代码的健壮性


我希望这能有所帮助。

myObject?.name?.bigThing?.let{first.text=it}
等每一行


etc

首先,更少的代码并不意味着更好的代码,但是在这种情况下,我们可以让它变得更简单。我希望解释一下,你的代码以增加阅读复杂性为代价节省了一些位;如果你想这样做,你应该使用
。但问题是关于减少if语句,所以我不同意这一部分:节省一些bits@pwolaq至于我同意的
方式,你可以将其作为答案发布