A tryOrNull function?

In some cases, we in fact only care about the operation is successful or not, but not the reason of Exception. For example, a file can have several parsing format or even a broken format. The parser will try each format until it’s successfully parsed. So the code maybe like this:

fun parse(): MyData? {
    	
    try {
        return parse1()
    } catch (e: Exception) {
	e.printStackTrace()
    }

    try {
	return parse2()
    } catch (e: Exception) {
	e.printStackTrace()
    }

    try {
	return parse3()
    } catch (e: Exception) {
	e.printStackTrace()
    }

    return null
 }

But isn’t it verbose? With a tryOrNull function it can be like this:

fun <T : Any> tryOrNull(body: () -> T?): T? {
    //the body returns T? so that you can give up the work by returning null
    return try {
	body()
    } catch (e: Exception) {
	e.printStackTrace()
	null
    }
}

fun parse(): MyData? {
    return tryOrNull { parse1() }
	?: tryOrNull { parse2() }
	?: tryOrNull { parse3() }
}

So far I use it from my private utils pack.
But, will this lovely function be adopted into the standard library :upside_down_face:?

You could always create a pull request here. And I would also check out arrow. It’s not for everyone but it is a great library if you use a more functional programming style. And classes like Try are always usefull :wink:

1 Like