require

Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
fun require(value: Boolean)

Throws an IllegalArgumentException if the value is false.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
fun getIndices(count: Int): List<Int> {
    require(count >= 0) { "Count must be non-negative, was $count" }
    // ...
    return List(count) { it + 1 }
}

// getIndices(-1) // will fail with IllegalArgumentException

println(getIndices(3)) // [1, 2, 3]
//sampleEnd
}
Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
inline fun require(value: Boolean, lazyMessage: () -> Any)

Throws an IllegalArgumentException with the result of calling lazyMessage if the value is false.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
fun getIndices(count: Int): List<Int> {
    require(count >= 0) { "Count must be non-negative, was $count" }
    // ...
    return List(count) { it + 1 }
}

// getIndices(-1) // will fail with IllegalArgumentException

println(getIndices(3)) // [1, 2, 3]
//sampleEnd
}

© 2010–2021 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/require.html