David Bieregger
06/22/2022, 4:02 PMtry {
throw Error("Oh no!")
} catch {
console.log("Something bad happened, but don't know what")
}
This saves you to write the unneccessary term: (e: Exception)
or (_: Throwable)
2. Elvis operator for exceptions maybe with a excalmation mark !:
?
var result = methodThatMightThrowAnError() !: return null
If you like it or not it's a very common pattern in libraries to use exceptions as method result. Even though the exception doesn't tell you any thing important it's essential to caputure those exceptions to know that the method didn't succeed.
A realworld example would be:
inline fun <reified T> validateSignedToken(token: String) =
try {
Json.decodeFromString<T>(jwtVerifier.verify(token).getClaim("payload").asString())
} catch (e: Exception) {
null
}
It can be reduced to:
inline fun <reified T> validateSignedToken(token: String) =
Json.decodeFromString<T>(jwtVerifier.verify(token).getClaim("payload").asString()) !: null
And yes it a bit a code golf, but I think this is Kotlin a lot about. Making thinks things very short and concise. When you don't need the Exception why spend writing the type for every try catch block?
I can imagine it beeing used in a Unit Testing project as follows:
fun insertTokenTest() {
assertNoException {
val person = fetchToken() !: "12345678" //This might cause an exception, but when it is not available we just don't mind an use an default value
Database.insertToken(person)
}
}
fun assertNoException(block: () -> Unit) =
block() !: throw Error("No exception is expected")
I think I have seen this operator already somewhere, but don't know where. Does this already have a name? Otherwise does somebody know a famous person with such a hairdo? ;)ephemient
06/22/2022, 4:39 PMassertNoException
as an exception fails the test to begin with, and 2. you don't want something like this for assertException
because you should always be clear which exception type you are expecting. this is how kotlin.test.assertFailsWith
and org.junit.jupiter.api.Assertions.assertThrows
work