Use Require

ID

kotlin.use_require

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Best Practice

Language

Kotlin

Tags

exception, precondition

Description

Reports throw IllegalArgumentException(…​) expressions. The Kotlin stdlib provides require(condition) { message } as a dedicated precondition helper with identical runtime semantics and clearer intent.

Rationale

Manual throw IllegalArgumentException(…​) is verbose and does not communicate that the site is a function-entry precondition. The require() function reads as a contract, uses a lazy message lambda to avoid string allocation on the happy path, and is idiomatic Kotlin.

// Bad
fun deposit(amount: Double) {
    if (amount <= 0) throw IllegalArgumentException("amount must be positive")  // FLAW
}

fun setName(name: String) {
    throw IllegalArgumentException("name must not be blank")  // FLAW
}

// Good
fun deposit(amount: Double) {
    require(amount > 0) { "amount must be positive" }
}

fun setName(name: String) {
    require(name.isNotBlank()) { "name must not be blank" }
}

Remediation

Replace throw IllegalArgumentException(msg) with require(condition) { msg }. When checking that a value is non-null, use requireNotNull(value) { msg } instead.