[英]Scala: Type mismatch required _$1 for lower context bound generics
我很難解決這種類型不匹配的編譯錯誤
我有一系列的 Sources 想要實現策略模式來處理適當的類型
sealed trait Source
case class SourceA extends Source
case class SourceB extends Source
我的預處理器包含許多處理適當案例類的策略
trait SourceStrategy[T <: Source] {
def isApplicable(source: Source): Boolean
def preprocess(source: T): Whatever
}
這個想法是對於上面的每個案例類都將存在一個 SourceStrategy 實現
我想做這樣的事情,通過適當的策略循環,找到適用的策略,然后調用該策略
class MyPreprocessor (strategies: Set[SourceStrategy[_ <: Source]]) {
def performPreprocessing(source: Source) = {
val preprocessor = strategies.filter(b => b.isApplicable(source)).head
preprocessor.preprocess(source)
}
}
我在最后一行中發現_$1
和Source
不匹配。
我了解發生這種情況的原因,但我不確定如何以干凈的方式解決它
您要么想在編譯時檢查當前策略是否適用於當前源,要么想在運行時檢查這一點。
如果你在運行時這樣做,那么讓SourceStrategy
泛型就沒有多大意義
trait SourceStrategy {
def isApplicable(source: Source): Boolean
def preprocess(source: Source): Whatever
}
class MyPreprocessor (strategies: Set[SourceStrategy]) {
def performPreprocessing(source: Source) = {
val preprocessor = strategies.filter(b => b.isApplicable(source)).head
preprocessor.preprocess(source)
}
}
如果您在編譯時這樣做,那么您可以使用異構集合和類型類
trait PerformPreprocessing[L <: HList, T <: Source] {
def performPreprocessing(strategies: L, source: T): Whatever
}
object PerformPreprocessing {
implicit def recur[T <: Source, S, L <: HList, T1 <: Source](implicit
performPreprocessing: PerformPreprocessing[L, T1]
): PerformPreprocessing[S :: L, T1] =
(strategies, source) => performPreprocessing.performPreprocessing(strategies.tail, source)
implicit def base[T <: Source, S <: SourceStrategy[T], L <: HList]: PerformPreprocessing[S :: L, T] =
(strategies, source) => strategies.head.preprocess(source)
}
class MyPreprocessor[L <: HList](strategies: L) {
def performPreprocessing[T <: Source](source: T)(implicit
performPreprocessing: PerformPreprocessing[L, T]
): Whatever =
performPreprocessing.performPreprocessing(strategies, source)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.