一般問題:定義型別為的泛型類的正確方法是什么,理想情況下在Scala 2中Numeric不使用任何型別?implicit
具體示例:考慮以下圍繞整數序列構建的玩具類:
class NewList(val values: Seq[Int]) {
def (x: Int): NewList = new NewList(values.map(_ x))
}
val x = new NewList(List(1,2,3))
(x 5).values // ---> List(6, 7, 8)
現在假設我們要進行NewList泛型,環繞任何數字序列:
// Would not compile
class NewList[T: Numeric](val values: Seq[T]) {
def (x: T): NewList = new NewList(values.map(_ x))
}
由于一些奇怪的型別不匹配,上面的代碼無法編譯
cmd2.sc:2: type mismatch;
found : T
required: String
def (x: T): NewList[T] = new NewList(values.map(_ x))
^Compilation Failed
Compilation Failed
據我了解,這個編譯錯誤顯然意味著編譯器無法將變數決議x: T為一種Numeric型別,因此無法決議plus. 嘗試在類定義或方法定義中宣告 (x: Numeric[T])或使用(implicit num: T => Numeric[T])都無濟于事。
使類編譯并按預期運行的唯一方法是使用plus方法implicitly[Numeric[T]]:
class NewList[T: Numeric](val values: Seq[T]) {
def (x: T): NewList[T] = new NewList(values.map(implicitly[Numeric[T]].plus(_, x)))
}
val x = new NewList(List(1,2,3))
(x 5).values // ---> List(6, 7, 8)
- 為什么編譯器無法決議 的方法
plus,T即使它Numeric在類定義中宣告? - 有沒有更好的方法來解決這個問題而不使用丑陋的樣板
implicitly[Numeric[T]].plus? - 一般來說,我們能否避免
implicit在 scala 中處理此類情況?
uj5u.com熱心網友回復:
為什么編譯器不能為 T 決議方法 plus,即使它在類定義中宣告為 Numeric?
首先,因為TIS NOT a Numeric; 而是它有一個與之關聯的Numeric typeclass
實體
其次,即使T是 a Numeric,它也沒有 方法;因為,再一次,這不是型別類的作業方式。
檢查這個:https ://gist.github.com/BalmungSan/c19557030181c0dc36533f3de7d7abf4
有沒有更好的方法來解決這個問題而無需隱式使用丑陋的樣板[Numeric[T]].plus?
是的,只需匯入擴展方法:import Numeric.Implicits._在頂層class或在方法內部。
一般來說,我們能否避免在 scala 中使用隱式處理這種情況?
[T: Numeric]只是糖語法,(implicit ev: Numeric[T])所以不,你無法避免implicits
這很好,真的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/455962.html
