gpt4 book ai didi

scala - 如何避免在具有家族多态性的 Scala 中调用 asInstanceOf

转载 作者:行者123 更新时间:2023-12-03 22:56:49 26 4
gpt4 key购买 nike

根据设计,我们确信我们有一个 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)
}
}

最佳答案

通常这样的事情有点类型优雅,所以我会这样做:

trait DailyFormatter[S] {
def formatDate(localDate: LocalDate): String
}
trait HourlyFormatter[S] {
def formatDateTime(localDateTime: LocalDateTime): String
}

implicit val dailyFormats: DailyFormatter[Daily]
implicit val hourFormats: DailyFormatter[Hourly] with HourlyFormatter[Hourly]

class Log[S <: StorageLayout](storageLayout: S, dateFormat: DateFormat[S]) {

def getPath(date: LocalDate)(implicit formater: DailyFormatter[S]): String =
formater.formatDate(date)

def getPath(date: LocalDateTime)(implicit formater: HourlyFormatter[S]): String =
formater.formatDateTime(date)
}
它的优点是您不必知道类型的存在 HourlyDateFormatDailyDateFormat使其工作。

关于scala - 如何避免在具有家族多态性的 Scala 中调用 asInstanceOf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62719829/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com