Kotlin KoansでKotlin入門 第15回:Ranges
5748 ワード
はじめに
公式の問題集「Kotlin Koans」を解きながらKotlinを学習します。
過去記事はこちら
- Introduction
- Classes
- Conventions
問題
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
}
fun checkInRange(date: MyDate, first: MyDate, last: MyDate): Boolean {
return date in first..last
}
Author And Source
この問題について(Kotlin KoansでKotlin入門 第15回:Ranges), 我々は、より多くの情報をここで見つけました https://qiita.com/kosuke1/items/797f049ce5f33b1810c9著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .