Hi, how do we pass the string parameter 'emessage...
# announcements
a
Hi, how do we pass the string parameter 'emessage' to the exception instance
Copy code
fun String?.throwOnEmptyOrNull(emessage: String, exceptionClass: Class<out Exception>): String {
    return this.takeIf { !it.isNullOrBlank() } ?: throw exceptionClass.newInstance()
}
Copy code
val ss : String? = null
println("test 1 ${ss.throwOnEmptyOrNull("roles can't be empty or not", IllegalArgumentException::class.java)}")
This is working for me, however i'm stuck at passing the message to exception
d
You should really consider passing in a factory function instead of relying on classes and reflection. However if you must, you have to use
getConstructor(String::class.java)
and then call
newInstance
on the constructor (this is using Java reflection).
a
@diesieben07 i'm really new writting factory function, i know it something like this
Copy code
fun <T>String?.throwOnEmptyOrNull(emessage: String, exceptionClass: T): String {
    return this.takeIf { !it.isNullOrBlank() } ?: throw exceptionClass.newInstance()
}
however i dont know the full syntax to complete this with constructor call
d
Copy code
fun String?.throwOnEmptyOrNull(emessage: String, exceptionFactory: (String) -> Throwable): String {
    return this.takeIf { !it.isNullOrBlank() } ?: throw exceptionFactory(emessage)
}

// usage:
"hello".throwOnEmptyOrNull("should not be empty", ::IllegalArgumentException)
e
built-in require/requireNotNull throw IllegalArgumentException:
Copy code
require(!ss.isNullOrEmpty()) { "roles can't be empty or not" }
also they work with smart casting (using contacts) and your function doesn't
d
True, I should have chosen a different example
e
to match the original example,
Copy code
println("test 1 ${requireNotNull(ss?.ifEmpty { null }) { "roles can't be empty or not" }}")
d
But that does not have the ability to pass in a custom exception class
a
@diesieben07 thank you that worked like a charm. However, i'm yet to understand how it works. What is the key word that i have to search to learn more about this feature ?
@ephemient thank you for your support as well
d
Higher order functions and lambdas
👍 1
e
::foo
is a reference, of which there are several types. in this case only one single-arg constructor can match the expected type, so
::IllegalArgumentException
is short for
{ it: String -> IllegalArgumentException(it) }
(with some minor differences you don't need to worry about)
👍 1
a
Thank you 🙂