棘手的类型边界

时间:2016-08-20 09:29:24

标签: scala

我正在尝试为ThreeTen's drop-in Scala reimplementation of java.time中的七个日期时间类创建一个参数化类Interval。我的班级签名看起来像这样:

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

TInstantLocalTimeOffsetDateTimeOffsetTime,但无法为LocalDate编译,{ {1}}和LocalDateTime,因为后三者不直接从ZonedDateTime继承。我无法为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*

1 个答案:

答案 0 :(得分:3)

我会采用与你的方法略有不同的方法,只需使用implicits和一个密封类型的家族来抽象出一切。这也使您有机会自己为没有定义的类实现排序。

int AuctionID

可以重写为:

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

现在,您可以安全地利用Scala允许您通过两种方式操作顺序这一事实,一种是通过继承实现Java的旧方法,(您将实现final case class Interval[ T <: Temporal with Serializable : Ordering ](start: T, end: T) ),或者在Scala的情况下, Comparable,另一个是Ordered,它总是通过隐式范围传递。

您可以通过提供独立于您的课程的订单来实现这一目标:

Ordering[T]

依此类推,适用于您需要订购的每种类型。

然后你就可以做到:

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