LoginSignup
0
0

More than 1 year has passed since last update.

Kotlin KoansでKotlin入門 第15回:Ranges

Posted at

はじめに

公式の問題集「Kotlin Koans」を解きながらKotlinを学習します。

過去記事はこちら

問題

Ranges

rangesを使用して、日付が最初の日付と最後の日付の間(を含む)の範囲にあるかどうかをチェックする関数を実装します。
任意の比較可能な要素から範囲を構築することができます。Kotlinでは、checksは対応するcontains呼び出しと...rangeTo呼び出しに変換されます。

val list = listOf("a", "b")
"a" in list  // list.contains("a")
"a" !in list // !list.contains("a")

date1..date2 // date1.rangeTo(date2)

修正前のコード

fun checkInRange(date: MyDate, first: MyDate, last: MyDate): Boolean {
    return TODO()
}

問題のポイント

range式は,in と !in で補われる演算子形式 ... を持つ rangeTo 関数で表現されます。

if (i in 1..10) { // 1 <= i && i <= 10 に相当
  println(i)
}

解答例

fun checkInRange(date: MyDate, first: MyDate, last: MyDate): Boolean {
    return date in first..last
}
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