我正在尝试创建一个简单的 api 来处理时间间隔。(我知道joda time,我不想重新发明它。这是一个练习)。
我想要实现的是:
(1)
assert(from("20:30").to("20:50") == Interval("20:30", "20:50") )
//same thing, but without implicit defs
assert(from(Time(20, 30)).to(Time(20, 50)) == Interval(Time(20, 30), Time(20, 50)))
(2)
assert(from("20:30").forMinutes(10) == from("20:30").to("20:40"))
我已经设法实现(1),如下所示:(忽略toString,Ordered trait,aso)
case class Time(hour: Int, minute: Int)
case class Interval(start: Time, end: Time)
object Interval {
case class HalfInterval(half: Time => Interval) {
def to(time: Time): Interval = half(time)
def forMinutes(minutes: Int): Interval = ???
}
def from(start: Time): HalfInterval = HalfInterval(Interval(start, _))
}
object Time {
def apply(hourMinute: String): Time = {
val tries = hourMinute.split(":").map(s => Try(s.toInt))
tries match {
case Array(Success(hour), Success(minute)) => Time(hour, minute)
case _ => throw new IllegalArgumentException
}
}
implicit def stringToTime(hourMinute: String) = Time(hourMinute)
}
但是,我不知道如何实现(2)(即:Interval.forMinutes)。
def forMinutes(minutes: Int): Interval = {
val time = ?? // Based on what Time object could I construct a new Time object here?
half(time)
}
似乎无法解决这个问题。
这个“HalfInterval”包装器是否Time => Interval
有意义?
我根据经验设计了它——只是为了让from(..).to(..)
调用按计划工作——而不是考虑到一些功能概念模型。
有没有更好的方法来实现这个api?
谢谢