如何创建 tryCatch 扩展函数

how to create tryCatch extension function

我喜欢实现这种代码:

someKindOfCode.tryCatch()

我创建了它,但 Any 没有完成这项工作,也没有将代码放入 tryCatch

private fun Any.tryCatch() {
    try {
        this
    } catch (e: Exception) {
        Log.e(TAG, "tryCatch: ", e)
    }
 }

您可以在 class 之外声明函数并在任何您想要的地方使用

fun <T> tryCatch(block: () -> T) =
    try {
        block()
    } catch (e: Exception) {
        e.printStackTrace()
    }

示例使用

class Test {

    fun testFun() {
        tryCatch {
            val res = 9 / 2
            res * 5
        }
    }
}

编辑 另一种选择,但看起来有点奇怪

fun <T> (() -> T).tryCatch() =
    try {
        this()
    } catch (e: Exception) {
        e.printStackTrace()
    }

例子

class Test {
    fun testFun() = {
        val res = 9 / 2
        res * 5
    }.tryCatch()
}