try without catch or smth like `tryOrElses` -> ...
# language-proposals
k
try without catch or smth like
tryOrElses
->
val t = try{...}
<- null on fail
val t = try{...} else X
val t = try{} ?: X
r
null on fail would loose the error type information
t
This can be done without changing the language. Have a look at https://arrow-kt.io/docs/arrow/core/try/
d
@katz you can also write your own util
try
function with such functionalty:
Copy code
inline fun <R> myTry(block: () -> R): R? {
    return try {
        block()
    } catch (e: Exception) {
        null
    }
}

fun test() {
    val x = myTry { ... } ?: 1
}
k
@raulraja some time you dont need error (for example i need to show image by url or else placeholder - and i dont care about error i can get as it will not help @dmitriy.novozhilov already using self crafter
tryOrElse
- it is suggestion to add such into kotlin core
l
i like the idea of having something like that, as its something i find my self implementing myself nearly on every project ;D just a little
tryOrNull
function would help a lot ;D
k
as option
try? {}
block
d
there is already existsing function
runCatching
in stdlib usage:
Copy code
val x = runCatching { ... }.getOrNull() ?: ...
5
l
I actively dislike
try?
as that would add New Syntax without ANY Benefit over an existing function. If were talking about Syntax changes, id rather have something like this:
Copy code
fun makeString(): String {
  throw Exception() 
} 
val foo: String? = makeString??()
// foo = null
So a Syntax that can turn any function that could throw into a function that can return null on exceptions. That would be great for chsining too
k
@Leon K not like that... i suggest
val foo:String? = try?{ makeString() }
@dmitriy.novozhilov loogs good, but tooo long... would be more... sweet just to have
val x = runCatching {...}
without calling
getorNull
... or i am just too lazy
j
Guys...
try
is already an expression in the language.
Copy code
val x: Int? = try { someIntExpression() } catch(e:Exception) { null }
l
We all know that. But now imagine having a chain of functions (where you DO NOT want to just Wrap everything in a try catch Statement) then having to write try catch 100 times really fucks up the readability. Having a Syntax that could turn a throwing function into a null returning one would greatly improve readability
r
And then having a syntax that works for all cases even better. That is what monad comprehensions do. Works for anything that has flatMap and covers the try, null and many other use cases that can be modeled in the same way. After all it's always sequencing effects in order the underlying root issue we struggle how to encode.