Skip to content

Instantly share code, notes, and snippets.

@mahata
Created January 8, 2018 13:09
Show Gist options
  • Save mahata/62b0e14603e9847d8aed40d15d107234 to your computer and use it in GitHub Desktop.
Save mahata/62b0e14603e9847d8aed40d15d107234 to your computer and use it in GitHub Desktop.
import java.util.Calendar
import TimeInterval.*
// 前提となるクラス群
enum class TimeInterval { DAY, WEEK, YEAR }
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int)
// RepeatedTimeInterval は TimeInterval と Int の値をプロパティとして持つ
// TimeInterval (すなわちDAY or WEEK or YEAR) が何回分 (Int) か、というデータ構造
class RepeatedTimeInterval(val timeInterval: TimeInterval, val number: Int)
// TimeInterval 型の `*` 演算子を定義している
// `TimeInterval * Int`で RepeatedTimeInterval オブジェクトが返る
operator fun TimeInterval.times(number: Int) = RepeatedTimeInterval(this, number)
// MyDate 型の `+` 演算子を定義している
// + の引数が TimeInterval のときと、RepeatedTimeInterval のときでオーバーロードしている
operator fun MyDate.plus(timeInterval: TimeInterval): MyDate = addTimeIntervals(timeInterval, 1)
operator fun MyDate.plus(timeIntervals: RepeatedTimeInterval) = addTimeIntervals(timeIntervals.timeInterval, timeIntervals.number)
fun MyDate.addTimeIntervals(timeInterval: TimeInterval, number: Int): MyDate {
val c = Calendar.getInstance()
c.set(year, month, dayOfMonth)
when (timeInterval) {
DAY -> c.add(Calendar.DAY_OF_MONTH, number)
WEEK -> c.add(Calendar.WEEK_OF_MONTH, number)
YEAR -> c.add(Calendar.YEAR, number)
}
return MyDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE))
}
fun task1(today: MyDate): MyDate {
return today + YEAR + WEEK
}
fun task2(today: MyDate): MyDate {
return today + YEAR * 2 + WEEK * 3 + DAY * 5
}
public fun main(args: Array<String>) {
val myDate = MyDate(2018, 1, 6)
println(task1(myDate)) // MyDate(year=2019, month=1, dayOfMonth=13)
println(task2(myDate)) // MyDate(year=2020, month=2, dayOfMonth=3)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment