본문 바로가기
코틀린/etc.

[Kotlin][Validation Operations] require

by jinwo_o 2024. 8. 16.

값이 false 인 경우 lazyMessage 를 호출한 결과와 함께 IllegalArgumentException 을 발생시킵니다.

public inline fun require(value: Boolean, lazyMessage: () -> Any): Unit {
    contract {
        returns() implies value
    }
    if (!value) {
        val message = lazyMessage()
        throw IllegalArgumentException(message.toString())
    }
}


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]

 

require - Kotlin Programming Language

 

kotlinlang.org

'코틀린 > etc.' 카테고리의 다른 글

[Kotlin][Iteration Operation] repeat  (0) 2024.08.27
[Kotlin][Collection] Mutable / Immutable  (0) 2024.08.07
[Kotlin][Input Operation] readln  (0) 2024.08.05