coerceIn

public fun <T : Comparable<T>> T.coerceIn(minimumValue: T?, maximumValue: T?): T {
    if (minimumValue !== null && maximumValue !== null) {
        if (minimumValue > maximumValue) throw IllegalArgumentException("Cannot coerce value to an empty range: maximum $maximumValue is less than minimum $minimumValue.")
        if (this < minimumValue) return minimumValue
        if (this > maximumValue) return maximumValue
    }
    else {
        if (minimumValue !== null && this < minimumValue) return minimumValue
        if (maximumValue !== null && this > maximumValue) return maximumValue
    }
    return this
}
fun main() {
		println(5.coerceIn(0, 10)) // 범위내에 있음. 기본값 반환 : 5
    println((-1).coerceIn(0, 50)) // 범위내에 없음. 최솟값 반환 : 0
    println(1000.coerceIn(0, 50)) // 범위내에 없음. 최댓값 반환 : 50
    println(1000.coerceIn(1..999)) // ..으로 범위연산 사용가능 최댓값 반환 : 999
}

coerceAtLeast

public fun <T : Comparable<T>> T.coerceAtLeast(minimumValue: T): T {
    return if (this < minimumValue) minimumValue else this
}
fun main() {
    println(5.coerceAtLeast(3)) // 최솟값 보다 기본값이 더 큼 : 5
    println(1.coerceAtLeast(3)) // 최솟값 보다 기본값이 더 작음 : 3
}

coerceAtMost

public fun <T : Comparable<T>> T.coerceAtMost(maximumValue: T): T {
    return if (this > maximumValue) maximumValue else this
}
fun main() {
    println(5.coerceAtMost(3)) // 최댓값 보다 기본값이 더 큼 : 3
    println(1.coerceAtMost(3)) // 최댓값 보다 기본값이 더 작음 : 1
}