【发布时间】:2020-07-25 23:14:38
【问题描述】:
我只是在学习 Kotlin Koans,所以我的问题可能非常愚蠢。
解决运算符重载一章我有两个文件,都在根级别:
第一个被错误标记为红色 - 我把它们作为 cmets
import TimeInterval // is gray
import addTimeIntervals // is gray
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int)
operator fun MyDate.plus(timeInterval: TimeInterval): MyDate
= MyDate.addTimeIntervals(Period(timeInterval, 1)) // Unresolved reference: addTimeIntervals
operator fun MyDate.plus(period: Period): MyDate
= MyDate.addTimeIntervals(period) //Unresolved reference: addTimeIntervals
fun task1(today: MyDate): MyDate {
return today + YEAR + WEEK // Unresolved reference: YEAR //Unresolved reference: WEEK
}
第二个没有错误:
import java.util.Calendar
/*
* Returns the date after the given time interval.
* The interval is specified as the given amount of days, weeks of years.
* Usages:
* 'date.addTimeIntervals(TimeInterval.DAY, 4)'
* 'date.addTimeIntervals(TimeInterval.WEEK, 3)'
*/
fun MyDate.addTimeIntervals(period: Period): MyDate {
val c = Calendar.getInstance()
c.set(year + if (period.timeInterval == TimeInterval.YEAR) period.amount else 0, month, dayOfMonth)
var timeInMillis = c.timeInMillis
val millisecondsInADay = 24 * 60 * 60 * 1000L
timeInMillis += period.amount * when (period.timeInterval) {
TimeInterval.DAY -> millisecondsInADay
TimeInterval.WEEK -> 7 * millisecondsInADay
TimeInterval.YEAR -> 0L
}
val result = Calendar.getInstance()
result.timeInMillis = timeInMillis
return MyDate(result.get(Calendar.YEAR), result.get(Calendar.MONTH), result.get(Calendar.DATE))
}
// Supported intervals that might be added to dates:
enum class TimeInterval { DAY, WEEK, YEAR}
operator fun TimeInterval.times(amount: Int): Period = Period(this, amount)
operator fun Int.times(timeInterval: TimeInterval): Period = timeInterval * this
data class Period(val timeInterval: TimeInterval, val amount: Int)
我不明白为什么第一个文件不能使用第二个文件的常量和扩展函数。将枚举类移动到第一个文件中不会改变任何内容。使用带有类名的常量确实有帮助,但整个主题是关于使代码简洁,因此,对于这种情况,这显然是一个错误的解决方案。
为什么它们不可见?
【问题讨论】:
标签: kotlin extension-methods visibility