Kotlin Koans - Conventions

Jmnote (토론 | 기여)님의 2019년 4월 7일 (일) 00:00 판 (→‎Range to)
# Kotlin Koans
Kotlin Koans - Introduction
Kotlin Koans - Conventions
Kotlin Koans - Collections
Kotlin Koans - Properties
Kotlin Koans - Builders
Kotlin Koans - Generics

1 Comparison

Kotlin
Copy
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
    override fun compareTo(other: MyDate) = when {
        year != other.year -> year - other.year
        month != other.month -> month - other.month
        else -> dayOfMonth - other.dayOfMonth
    }
}

fun compare(date1: MyDate, date2: MyDate) = date1 < date2

2 In range

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

fun checkInRange(date: MyDate, first: MyDate, last: MyDate): Boolean {
    return date in DateRange(first, last)
}
MyDate.kt
Kotlin
Copy
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
    override fun compareTo(other: MyDate) = when {
        year != other.year -> year - other.year
        month != other.month -> month - other.month
        else -> dayOfMonth - other.dayOfMonth
    }
}

3 Range to

Kotlin
Copy
operator fun MyDate.rangeTo(other: MyDate) = DateRange(this, other)

class DateRange(override val start: MyDate, override val endInclusive: MyDate): ClosedRange<MyDate>

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

4 For loop

Kotlin

5 Operators overloading

Kotlin

6 Destructuring declarations

Kotlin

7 Invoke

Kotlin