2016-08-20 70 views
0

我试图为ThreeTen's drop-in Scala reimplementation of java.time中的七个日期时间类创建参数化类Interval。我班的签名看起来是这样的:Tricky类型边界

final case class Interval[T <: Temporal with Ordered[T] with Serializable](start: T, end: T) 

能正常工作时TInstantLocalTimeOffsetDateTime,或OffsetTime,但未能编译LocalDateLocalDateTimeZonedDateTime因为后三个不直接继承从Ordered[T]。我无法提供适用于所有七个人的Interval[T]的正确类型签名。

有更多经验的人能帮我一个忙吗?特别感谢您解释答案背后的理论!

仅供参考,这里有七个日期时间类的签名:

final class Instant private(private val seconds: Long, private val nanos: Int) extends TemporalAccessor with Temporal with TemporalAdjuster with Ordered[Instant] with Serializable 
final class LocalTime(_hour: Int, _minute: Int, _second: Int, private val nano: Int) extends TemporalAccessor with Temporal with TemporalAdjuster with Ordered[LocalTime] with Serializable 
final class OffsetDateTime private(private val dateTime: LocalDateTime, private val offset: ZoneOffset) extends Temporal with TemporalAdjuster with Ordered[OffsetDateTime] with Serializable 
final class OffsetTime(private val time: LocalTime, private val offset: ZoneOffset) extends TemporalAccessor with Temporal with TemporalAdjuster with Ordered[OffsetTime] with Serializable 
final class LocalDate private(private val year: Int, monthOfYear: Int, dayOfMonth: Int) extends ChronoLocalDate with Temporal with TemporalAdjuster with Serializable 
final class LocalDateTime private(private val date: LocalDate, private val time: LocalTime) extends ChronoLocalDateTime[LocalDate] with Temporal with TemporalAdjuster with Serializable 
final class ZonedDateTime(private val dateTime: LocalDateTime, private val offset: ZoneOffset, private val zone: ZoneId) extends ChronoZonedDateTime[LocalDate] with Temporal with Serializable 

下面是对于那些过去三年Chrono*性状类特征:

trait ChronoLocalDate extends Temporal with TemporalAdjuster with Ordered[ChronoLocalDate] 
trait ChronoLocalDateTime[D <: ChronoLocalDate] extends Temporal with TemporalAdjuster with Ordered[ChronoLocalDateTime[_]] 
trait ChronoZonedDateTime[D <: ChronoLocalDate] extends Temporal with Ordered[ChronoZonedDateTime[_]] 

回答

2

我将采取略有不同的方法而不是你所拥有的那种,只是使用暗示和一个密封的家庭来抽象掉一切。这也可以让你有机会为没有定义的类定制自己的类。

final case class Interval[ 
    T <: Temporal with Serializable 
](start: T, end: T)(implicit def ordering: Ordering[T]) 

哪些可以重新写为:

final case class Interval[ 
    T <: Temporal with Serializable : Ordering 
](start: T, end: T) 

您现在可以安全地利用的事实,斯卡拉让您操作顺序的2种方式,一种是爪哇老同学的方式通过继承, (你将实现Comparable),或者在斯卡拉的情况下,Ordered,另一个是Ordering[T],它总是通过隐式范围。

而且你可以做到这一点通过提供顺序无关你的类:

object TimeOrdering { 
    implicit object ChronoLocalDateOrdering extends Ordering[ChronoLocalDate] { 
    override def compare(x: ChronoLocalDate, y: ChronoLocalDate): Int = ??? 
    } 
} 

等等,对每一个地方,你需要订购类型。

然后,你可以简单地做:

val x: ChronoLocalDate = ... 
val y: ChronoLocalDate = ... 
import TimeOrdering._ // to get the implicits in scope. 
val interval = Interval(x, y)