kotlin - 我的情况下IF的减少数量

标签 kotlin

我的方法中这样的IF太多:

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

还有20个...

如何缩短代码?
age/surname/name是使用Bigid: Int输入我自己的类bigThing: String

最佳答案

一种方法是:

myObject?.age?.let { second.text = it.bigThing }

如果要将值放在TextView中:
first.text = myObject?.age?.bigThing

关于kotlin - 我的情况下IF的减少数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51486857/

相关文章:

arrays - 如何用值初始化 Kotlin 中的数组?

generics - 从 lambda 参数推导时,Kotlin 泛型失败

android - 根据Appbar的偏移量或高度调整 View 大小

android - OkHttpClient 有时会收到不完整的 json 响应

angular - 如何使服务器发送事件(SSE)通过 Zuul 代理 spring-boot 2.1.1 工作

android - 如何使用可为空的参数模拟私有(private)方法

kotlin - 检查字符串是否只包含字母

android - Kotlin使用TikXml解析XML文件

jvm - 在 Kotlin 中,如何惯用地访问可为空的嵌套映射值,或返回默认值?

Android Firebase PERMISSION_DENIED 原因 API_KEY_SERVICE_BLOCKED