編譯器知道關於類型的更多信息,而不是JVM運行時可以輕鬆表示的信息。 Manifest是編譯器在運行時向代碼發送間維信息的一種方式,用於說明丟失的類型信息。
這與Kleptonians如何在化石記錄中留下編碼信息和人類的「垃圾」DNA相似。由於光速和重力場的限制,它們無法直接通信。但是,如果你知道如何調諧他們的信號,你可以以你無法想象的方式獲益,從決定午餐吃什麼或吃哪個樂透號碼。
如果一個清單會在不瞭解更多細節的情況下有利於您看到的錯誤,那麼目前尚不清楚。
Manifests的一個常見用法是讓您的代碼根據集合的靜態類型行爲不同。例如,如果你想從其他類型的列表的區別對待列表[字符串]什麼:
def foo[T](x: List[T])(implicit m: Manifest[T]) = {
if (m <:< manifest[String])
println("Hey, this list is full of strings")
else
println("Non-stringy list")
}
foo(List("one", "two")) // Hey, this list is full of strings
foo(List(1, 2)) // Non-stringy list
foo(List("one", 2)) // Non-stringy list
基於反射的解決方案,這可能會涉及到檢查列表中的每個元素。
結合上下文,似乎最適合於使用階型類,並深受Debasish戈什這裏解釋: http://debasishg.blogspot.com/2010/06/scala-implicits-type-classes-here-i.html
上下文範圍也可以只使該方法的簽名更具可讀性。例如,上述功能可以使用上下文範圍,像這樣重新編寫:
def foo[T: Manifest](x: List[T]) = {
if (manifest[T] <:< manifest[String])
println("Hey, this list is full of strings")
else
println("Non-stringy list")
}
關於Manifest/ClassManifest差異的討論已在郵件列表中進行了討論,請參閱http://scala-programming-language.1934581.n4.nabble.com/What-s-the-difference-between-ClassManifest-和 - Manifest-td2125122.html – 2010-07-09 23:23:57
另請參見:[Scala:什麼是TypeTag,我該如何使用它?](http://stackoverflow.com/questions/12218641/scala-what-is-a-typetag-and如何使用它) – Jesper 2015-10-09 10:31:49