[毎日Kotlin] Day16. In range

2018.02.02

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

はじめに

毎日Kotlinシリーズです。

このシリーズを初めての方はこちらです。「毎日Kotlin」はじめました | Developers.IO

問題

In range | Try Kotlin

今日もオレオレ演算子ルールを作ってみましょう。

In range In Kotlin in checks are translated to the corresponding contains calls:

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

Read about ranges. Add a method fun contains(d: MyDate) to the class DateRange to allow in checks with a range of dates.

class DateRange(val start: MyDate, val endInclusive: MyDate)

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

狙い

ここで考えて欲しい問題の意図はなんだろうか?

[毎日Kotlin] Day15. Comparison(演算子)の復習問題です。

手を動かしてやってみよう。

解答例

class DateRange(val start: MyDate, val endInclusive: MyDate) {
    operator fun contains(item: MyDate): Boolean = start <= item && item <= endInclusive
}

これ以外にも解答は2つあります。なんだったかなっという方は、[毎日Kotlin] Day15. Comparison(演算子)で復習しよう。

あとがき

Day17.でまたお会いしましょう。