Search code examples
androidkotlinkotlin-extension

how to create tryCatch extension function


i like to achieve this kind of code:

someKindOfCode.tryCatch()

i kind of created it but Any doesn't do the job and don't put the code inside of tryCatch

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

Solution

  • You can declare functions outside the class and use wherever you want

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

    example using

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

    EDIT another option, but it looks a little strange

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

    example

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