我有以下的情況下類:如何用case類處理簡單的多態性?
object Fields {
abstract class Base{
def getString: String
}
case class A() extends Base{
def getString = "A+++"
}
case class B() extends Base{
def getString = "B++"
}
def fieldsToString(fields: List[Base]): String = {
fields.tail.foldLeft(s"${fields.head.getString}") {(acc, f) =>
acc + s",${f.getString}"
}
}
}
然後我試圖調用此函數以下列方式:
val fields = List(A, B, A)
val result = Fields.fieldsToString(fields)
使我有以下錯誤:
type mismatch;
[error] found : List[scala.runtime.AbstractFunction0[Product with Serializable
with Fields.Base] with Serializable]
所以我想我需要引入協變:
def fieldsToString[T >: Base](fields: List[T]): String = {
fields.tail.foldLeft(s"${fields.head.getString}") {(acc, f) =>
acc + s",${f.getString}"
}
}
,然後給了我下面的編譯錯誤:
do not conform to method fieldsToString's type parameter bounds [T <: Fields.Base]
到底是什麼問題,這是因外殼班,難道他們不同的表現則正常上課?