我遇到以下代碼(嚴重簡化)的問題。看起來問題可能與我使用抽象類型成員的方式有關。我希望有人指出並解釋我在這裏做錯了什麼。編譯器錯誤在底部。 我正在使用Scala版本2.12。如何在Scala中使用抽象類型成員
trait DataType {
type A
def convert(value: String): A
def convertToString(value: A): String
}
case object IntType extends DataType {
type A = Int
def convert(value: String): A = value.toInt
def convertToString(value: A): String = value.toString
}
trait Codec[T <: DataType] {
val dtype: T
def encode(data: Array[String]): Array[T#A]
def decode(data: Array[T#A]): Array[String]
}
class CodecImp[T <: DataType](val dtype: T)(implicit tag: ClassTag[T#A]) extends Codec[T] {
def encode(data: Array[String]): Array[T#A] = {
Array[T#A](dtype.convert(data(0)))
}
def decode(data: Array[T#A]): Array[String] = {
Array[String](dtype.convertToString(data(0)))
}
}
val cod = new CodecImp(IntType)
val encoded = cod.encode(Array("1", "2", "3")) // expecting: Array[IntType.A]
val decoded = cod.decode(encoded) // expecting: Array[String]
編譯器錯誤。
Error:(30, 50) type mismatch;
found : T#A
required: CodecImp.this.dtype.A
Array[String](dtype.convertToString(data(0)))
^
謝謝。我實際上在這裏使用過類型參數,但想要嘗試嵌套類型。 –