19

KotlinTips: getValueSafely 安全取值 - 技术小黑屋

 4 years ago
source link: https://droidyue.com/blog/2020/03/22/kotlin-tips-get-value-safely/?
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

diuwuxian_course.png

KotlinTips: getValueSafely 安全取值

Mar 22nd, 2020

  • 安全取值,增加稳定性
  • 规避繁琐的显式try-catch处理
1
2
3
4
5
6
7
8
9
10
11
12
/**
 * 安全的获取值的信息,其过程中发生异常会自动处理,返回null
 * getValueAction 取值操作,可能发生异常
 * */
inline fun <T> getValueSafely(getValueAction: () -> T?): T? {
    return try {
        getValueAction()
    } catch(t: Throwable) {
        t.printStackTrace()
        null
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
fun testGetValueSafely() {
    val value1 = getValueSafely {
        1/ 0
  }

    val value2 = getValueSafely {
        1 + 1
  }

  value1.printLog()
  value2.printLog()
}
1
2
03-21 16:55:05.649  5072  5072 I KotlinTips: null
03-21 16:55:05.649  5072  5072 I KotlinTips: 2

关于 KotlinTips

KotlinTips是一个关于Kotlin编码技巧的一个系列,希望通过轻量简单的形式介绍能对大家有帮助。

Posted by androidyue Mar 22nd, 2020Kotlin, KotlinTips, null, 异常

« 微信支付 核心业务应用工程师(深圳/广州) 招聘内推 KotlinTips elvis 快速返回 »


Gitalk 加载中 ...


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK