明顯的比較之後,我有一些問題,即A <: Array[_]
鑄造兩個數組中階
我創建了一個功能比較manifest
和投數據到陣列向好型投我objeсtVariable[A]
。
我的目標Variable[A]
商店Manifest[A]
到DEF 'type'
我做一個存在軟件的插件,所以它不是我哪個實例化這個Variable
具有良好的類型。
原型對象和類:
object Prototype {
def apply[T](n: String)(implicit t: Manifest[T]) = new Prototype[T] {
val name = n
val `type` = t
}
}
trait Prototype[T] {
def name: String
def `type`: Manifest[T]
}
可變對象和類:
object Variable {
def apply[T](p: Prototype[T], v: T) = new Variable[T] {
val prototype = p
val value = v
}
}
trait Variable[T] {
def prototype: Prototype[T]
def value: T
}
我的類,它使用:
class XYDataReader[A <: Array[_]](var data: Iterable[Variable[A]]) {
def get[T](variable: Variable[A])(implicit m: Manifest[T]): Option[T] = {
if (variable.prototype.`type` <:< m) {
Some(variable.value.asInstanceOf[T])
} else {
None
}
}
}
有可能是我的一部分的一個錯誤,當我instanciate用於比較的變量對象,所以我給了instanciation的代碼:
val v:List[Any] = List[Any](1.2,2,3)
val p = Prototype[Array[Any]]("col1")
val myVariable = Variable(p, v.toArray(ClassTag(p.`type`.runtimeClass)))
我不理解爲什麼圖案匹配失敗時,我打電話get[Array[Double]](myVariable)
其中myVariable.value
含有Array[Double]
當我println()
的兩個清單:
- 變量數組類型:
Array[double]
- m型:
Array[Double]
它似乎是一個Array[Double]
不是Array[double]
,我該如何解決/施放此?
K記住Scala的'Array'是一個JVM'Array',它們是_invariant_。因此,沒有兩個不同的'Array'類型彼此以子類型關係站立。 –
我認爲最好的建議是避免初學者使用Array。其次,至少要公開地避免施法。 Scala模式匹配是處理動態類型決策的更好方法。 –
我嘗試在我的代碼中使用這種方法在現實中:http://stackoverflow.com/questions/3213510/what-is-a-manifest-in-scala-and-when-do-you-need-it;但它在鏈接工作可能是因爲它使用List而不是Array ... – reyman64