althaf
08/14/2021, 4:20 PMfun String?.throwOnEmptyOrNull(emessage: String, exceptionClass: Class<out Exception>): String {
return this.takeIf { !it.isNullOrBlank() } ?: throw exceptionClass.newInstance()
}
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 exceptiondiesieben07
08/14/2021, 4:26 PMgetConstructor(String::class.java)
and then call newInstance
on the constructor (this is using Java reflection).althaf
08/14/2021, 4:40 PMfun <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 calldiesieben07
08/14/2021, 4:42 PMfun String?.throwOnEmptyOrNull(emessage: String, exceptionFactory: (String) -> Throwable): String {
return this.takeIf { !it.isNullOrBlank() } ?: throw exceptionFactory(emessage)
}
// usage:
"hello".throwOnEmptyOrNull("should not be empty", ::IllegalArgumentException)
ephemient
08/14/2021, 4:45 PMrequire(!ss.isNullOrEmpty()) { "roles can't be empty or not" }
ephemient
08/14/2021, 4:46 PMdiesieben07
08/14/2021, 4:46 PMephemient
08/14/2021, 4:49 PMprintln("test 1 ${requireNotNull(ss?.ifEmpty { null }) { "roles can't be empty or not" }}")
diesieben07
08/14/2021, 4:53 PMalthaf
08/14/2021, 5:03 PMalthaf
08/14/2021, 5:03 PMdiesieben07
08/14/2021, 5:07 PMdiesieben07
08/14/2021, 5:07 PMephemient
08/14/2021, 5:11 PM::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)althaf
08/14/2021, 5:15 PM