Guest User

Untitled

a guest
Jan 16th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. import java.util.Calendar
  2. import TimeInterval.*
  3.  
  4. // 前提となるクラス群
  5. enum class TimeInterval { DAY, WEEK, YEAR }
  6. data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int)
  7.  
  8. // RepeatedTimeInterval は TimeInterval と Int の値をプロパティとして持つ
  9. // TimeInterval (すなわちDAY or WEEK or YEAR) が何回分 (Int) か、というデータ構造
  10. class RepeatedTimeInterval(val timeInterval: TimeInterval, val number: Int)
  11.  
  12. // TimeInterval 型の `*` 演算子を定義している
  13. // `TimeInterval * Int`で RepeatedTimeInterval オブジェクトが返る
  14. operator fun TimeInterval.times(number: Int) = RepeatedTimeInterval(this, number)
  15.  
  16. // MyDate 型の `+` 演算子を定義している
  17. // + の引数が TimeInterval のときと、RepeatedTimeInterval のときでオーバーロードしている
  18. operator fun MyDate.plus(timeInterval: TimeInterval): MyDate = addTimeIntervals(timeInterval, 1)
  19. operator fun MyDate.plus(timeIntervals: RepeatedTimeInterval) = addTimeIntervals(timeIntervals.timeInterval, timeIntervals.number)
  20.  
  21. fun MyDate.addTimeIntervals(timeInterval: TimeInterval, number: Int): MyDate {
  22. val c = Calendar.getInstance()
  23. c.set(year, month, dayOfMonth)
  24. when (timeInterval) {
  25. DAY -> c.add(Calendar.DAY_OF_MONTH, number)
  26. WEEK -> c.add(Calendar.WEEK_OF_MONTH, number)
  27. YEAR -> c.add(Calendar.YEAR, number)
  28. }
  29. return MyDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE))
  30. }
  31.  
  32. fun task1(today: MyDate): MyDate {
  33. return today + YEAR + WEEK
  34. }
  35.  
  36. fun task2(today: MyDate): MyDate {
  37. return today + YEAR * 2 + WEEK * 3 + DAY * 5
  38. }
  39.  
  40. public fun main(args: Array<String>) {
  41. val myDate = MyDate(2018, 1, 6)
  42. println(task1(myDate)) // MyDate(year=2019, month=1, dayOfMonth=13)
  43. println(task2(myDate)) // MyDate(year=2020, month=2, dayOfMonth=3)
  44. }
Add Comment
Please, Sign In to add comment