実践
早速ですが実践です。
var x = 2
var y = 11
println(x.coerceIn(0, 10)) // 2
println(y.coerceIn(0, 10)) // 10
coerceInという関数の引数内で範囲を指定することで、その範囲を外れた場合 指定した範囲に矯正してくれるというものです。
coerceInを変換すると ”強制する”というそのまま出てきますので、わかりやすいです。
var y = 11
var x = 2
if(x < 0){
x = 0
} else if(x > 10 ){
x = 10
}
if(y < 0){
y = 0
} else if(y > 10 ){
y = 10
}
println(x.coerceIn(0, 10))
println(y.coerceIn(0, 10))
このように書いていたものが かなり縮めて書くことができますね。
実践2
下限だけの範囲、上限だけの範囲を指定することもできます。
var x = 2
var y = 11
var z = -1
println(x.coerceAtLeast(0)) // 2
println(y.coerceAtLeast(0)) // 11
println(z.coerceAtLeast(0)) // 0
println(x.coerceAtMost(10)) // 2
println(y.coerceAtMost(10)) // 10
println(z.coerceAtMost(10)) // -1
下限のみを指定する場合は coerceAtLeast
上限のみを指定する場合は coerceAtMost
参考