Another extension option. I was looking for a way of validating a bunch of strings and then using them, and the nested blocks are a pain for reading in that aspect.
fun String?.notNullOrEmpty(illegalArgumentExceptionMsg: String): String {
return if (this == null || this.isEmpty()) throw IllegalArgumentException(illegalArgumentExceptionMsg) else this
}
simple use
val myNullOrEmptyString: String? = "bar"
val myNotNullString = myNullOrEmptyString.notNullOrEmpty("myNullOrEmptyString should not be empty")
use
val myNullOrEmptyString: String? = "bar"
val myNotNullString: String = myNullOrEmptyString.notNullOrEmpty("myNullOrEmptyString should not be empty")
Test or uses
@Test
fun emptyNotNullExtension() {
val msg = "foo"
assertThatThrownBy {
val emptyNotNullString: String = "".notNullOrEmpty(msg)
}
.isExactlyInstanceOf(IllegalArgumentException::class.java)
.hasMessageContaining(msg)
assertThatThrownBy {
val emptyNotNullString: String = null.notNullOrEmpty(msg)
}
.isExactlyInstanceOf(IllegalArgumentException::class.java)
.hasMessageContaining(msg)
val myNullOrEmptyString: String? = "bar"
val myNotNullString: String = myNullOrEmptyString.notNullOrEmpty("myNullOrEmptyString should not be empty")
}