0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

KotlinでcoerceIn / coerceAtLeast で範囲外の値を安全にクランプする

0
Posted at

はじめに

例えば、音量スライダーなどを作る際に使用すると便利な拡張関数coerceIn、coerceAtLeastなどを紹介します。
役割としては、「値を指定した範囲に収める」という点です。
音量スライダーを実装しようとすると、以下のような要素を書く必要があります。

  • 範囲:0〜100
  • ユーザーが 150 を入力しても → 100 に丸める
  • -10 を入力しても → 0 に丸める

これを毎回 if で書くと面倒ですが、coerceIn を使えば1行です。

   val volume = userInput.coerceIn(0, 100)        

以下ではそれぞれのパターンの範囲をカバーできるものを書いていきます。

coerceIn 上限・下限の両方を指定

val ratio = (distanceKm / gridMax).coerceIn(0f, 1f)
値が範囲外でも安全に収まります。

1.5f.coerceIn(0f, 1f)  // 1.0f                                                
-0.3f.coerceIn(0f, 1f) // 0.0f                                     
0.7f.coerceIn(0f, 1f)  // 0.7f(そのまま)

if で書くとこうなります。coerceIn の方が意図が明確です。

if (value < 0f) 0f else if (value > 1f) 1f else value  

coerceAtLeast 下限だけ指定

「最低でもこの値以上」という場合に使います。

  (-5f).coerceAtLeast(0f) // 0.0f                                                                                                                           
  1f.coerceAtLeast(2f)    // 2.0f                                                                                                                         
  3f.coerceAtLeast(2f)    // 3.0f(そのまま)                                    

coerceAtMost 上限だけ指定

  5f.coerceAtMost(3f) // 3.0f      

まとめ表

関数 用途
coerceIn(min, max) 上限・下限の両方を丸める
coerceAtLeast(min) 下限だけ保証する
coerceAtMost(max) 上限だけ保証する
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?