Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

throw if operator in Kotlin

Tags:

kotlin

What would be a more elegant way to rewrite the below code in kotlin.

if (xList.isEmpty()) {
   throw SomeException("xList was empty")
}

Do we have a throwif operator or something?

like image 642
S..K Avatar asked Nov 10 '17 12:11

S..K


3 Answers

Yet another suggestion, terse and not requiring additional code :

xList.isNotEmpty() || throw SomeException("xList was empty")

It works because throw is an expression, having the type Nothing which is a subtype of everything, including Boolean.

like image 166
bwt Avatar answered Oct 06 '22 02:10

bwt


I like to use the takeIf standard function to validate, with elvis operator addition, it gives this:

xList.takeIf { it.isNotEmpty() } ?: throw SomeException("xList was empty")
    

I have to add that in most cases an IllegalArgumentException is what I need, and it is simpler to just use require.
In cases that we need an IllegalStateException, we can rather use check.

See also: checkNotNull, requireNotNull, error

like image 21
crgarridos Avatar answered Oct 06 '22 01:10

crgarridos


I don't know of a function in the standard library, but you can easily do this yourself:

/**
 * Generic function, evaluates [thr] and throws the exception returned by it only if [condition] is true
 */
inline fun throwIf(condition: Boolean, thr: () -> Throwable) {
    if(condition) {
        throw thr()
    }
}

/**
 * Throws [IllegalArgumentException] if this list is empty, otherwise returns this list.
 */
fun <T> List<T>.requireNotEmpty(message: String = "List was empty"): List<T> {
    throwIf(this.isEmpty()) { IllegalArgumentException(message) }
    return this
}

// Usage
fun main(args: Array<String>) {
    val list: List<Int> = TODO()
    list.filter { it > 3 }
        .requireNotEmpty()
        .forEach(::println)
}
like image 32
Robin Avatar answered Oct 06 '22 01:10

Robin