class TestClass[T](val x: T) { def +(other: TestClass[T]) = x + other.x }
參數類型+函數需要一個字符串作爲第二個參數?
這個定義給了我下面的編譯錯誤:
錯誤:類型不匹配;
發現:T
需要:字符串
DEF +(其它:識別TestClass [T])= X + other.x
是它不可能使用int或double作爲類型參數,並使用另外Scala中??
class TestClass[T](val x: T) { def +(other: TestClass[T]) = x + other.x }
參數類型+函數需要一個字符串作爲第二個參數?
這個定義給了我下面的編譯錯誤:
錯誤:類型不匹配;
發現:T
需要:字符串
DEF +(其它:識別TestClass [T])= X + other.x
是它不可能使用int或double作爲類型參數,並使用另外Scala中??
首先,錯誤信息是誤導性的。 scalac試圖找到一個值x
的方法+
。這在類型T
上不存在,其可以是任何類型。這被稱爲無限類型參數。所以它試圖應用和隱含的觀點。 Predef.any2stringadd
符合法案。
您可以禁用此隱式轉換,並看到真正的錯誤:
~/code/scratch: cat plus.scala
import Predef.{any2stringadd => _, _}
class TestClass[T](val x: T) {
def +(other: TestClass[T]) = x + other.x
}
~/code/scratch: scalac plus.scala
plus.scala:4: error: value + is not a member of type parameter T
def +(other: TestClass[T]) = x + other.x
^
one error found
在C++中,提供了類型參數後的類型檢查完成後,在每個調用站點。所以這種風格的代碼將起作用。在Scala中,泛型方法必須根據其定義進行類型檢查,僅基於抽象類型的邊界。
正如VonC所建議的那樣,您可能希望提供一個上下文綁定在類型參數T
上,以約束是否具有對應於Numeric
特徵的實例的類型。
class TestClass[T: Numeric](val x: T) {
def +(other: TestClass[T]): T = {
val num = implicitly[Numeric[T]]
import num._
x + other.x
}
}
以下是這看起來與所有的implicits作出了明確:
class TestClass[T]{
implicit <paramaccessor> private[this] val evidence$1: Numeric[T] = _;
def this(x: T)(implicit evidence$1: Numeric[T]): TestClass[T] = {
TestClass.super.this();
()
};
def +(other: TestClass[T]): T = {
val num: Numeric[T] = scala.Predef.implicitly[Numeric[T]](TestClass.this.evidence$1);
import num._;
num.mkNumericOps(TestClass.this.x).+(other.x)
}
}
見http://stackoverflow.com/questions/2096414/addition-with-generic-type-parameter-in-scala和http://stackoverflow.com/questions/1252915/scala-how-to-define-generic-function-parameters初學者:你可能需要一個隱式的''數字''類型'T'在這裏。 – VonC 2010-06-27 16:15:34