I have a set of functions that have different signatures and parameters, but all of them could throw an exception. Instead of adding try-catch in each of them, I want to write an inline function that takes a function as an argument and calls this function within a try-catch block, and returns are certain types wrapping the exception.
// first function.
fun foo() -> String
// second function.
fun bar(argument: String) -> Boolean
// Result Type
sealed class Result<out R> {
data class Success<out T>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
}
// Wrapper Function
inline fun <T, R> safeCall(call: (T) -> R): Result<R>
// This Returns Result<String>
safeCall {
foo()
}
// This Returns Result<Boolean>
safeCall {
bar()
}
I am facing an issue while implementing the safeCall() method. Ideally, I would want this to work for any underlying function. I can either make it to work for foo() or bar(argument: String) but not for both.
inline fun <T, R> safeCall(
call: (T) -> R, // This syntax forces to to have only one parameter.
): Result<R> {
return try {
val result: R = call() // This throws compilation error.
Result.Success(result)
} catch (e: Exception) {
Result.Error(e)
}
}
PS - Pretty new to Kotlin and Functional Programming.