【发布时间】:2020-07-04 06:16:40
【问题描述】:
根据设计,我们确定我们有一个 HourlyDateFormat 的实例
在这种情况下如何避免调用 asInstanceOf (即如何帮助编译器推断类型)?
sealed trait StorageLayout extends Product with Serializable
case object Hourly extends StorageLayout
case object Daily extends StorageLayout
sealed trait DateFormat[S <: StorageLayout]
sealed abstract class HourlyDateFormat extends DateFormat[Hourly.type] {
def format(localDate: LocalDate): String = ???
def format(localDateTime: LocalDateTime): String = ???
}
sealed abstract class DailyDateFormat extends DateFormat[Daily.type] {
def format(localDate: LocalDate): String = ???
}
class Log[S <: StorageLayout](storageLayout: S, dateFormat: DateFormat[S]) {
def getPath(date: LocalDate): String =
dateFormat match {
case hdf: HourlyDateFormat => hdf.format(date)
case ddf: DailyDateFormat => ddf.format(date)
}
@SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf"))
def getPath(date: LocalDateTime)(implicit ev: S =:= Hourly.type): String = {
assert(ev == ev)
dateFormat.asInstanceOf[HourlyDateFormat].format(date)
}
}
【问题讨论】:
-
如果你能描述一下你可以改变什么,你的最终目标是什么,这可能会有所帮助?你想怎么用
Log?