Reputation: 9143
I'm doing Kotlin Koans's Operator Overloading exercise and am wondering how the compiler chooses which MyDate.plus()
function to use:
import TimeInterval.*
import java.util.Calendar
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int)
enum class TimeInterval { DAY, WEEK, YEAR }
operator fun MyDate.plus(timeInterval: TimeInterval) = addTimeIntervals(timeInterval, 1)
class FullTimeInterval(val timeInterval: TimeInterval, val number: Int)
operator fun TimeInterval.times(number: Int) = FullTimeInterval(this, number)
operator fun MyDate.plus(timeIntervals: FullTimeInterval)
= addTimeIntervals(timeIntervals.timeInterval, timeIntervals.number)
fun task1(today: MyDate): MyDate {
return today + YEAR + WEEK
}
fun task2(today: MyDate): MyDate {
return today + YEAR * 2 + WEEK * 3 + DAY * 5
}
Upvotes: 0
Views: 68
Reputation: 4992
You have two classes: TimeInterval
and FullTimeInterval
and two overloaded functions:
MyDate.plus(timeIntervals: TimeInterval)
and MyDate.plus(timeIntervals: FullTimeInterval)
The compiler knows the type of the argument and it selects the closest function by the signature. The decision is made at the compilation time and depends on the computed types of the arguments.
You may find more information on that at https://jetbrains.github.io/kotlin-spec/#overload-resolution
Upvotes: 2