我對Scala很新穎。我想寫幾個在某些操作(+, - ,*)下關閉的數學對象(Complex,Polynomial等),以便可以在泛型中使用它們,並且可以使用隱式轉換。實現編號
我似乎已經解決了第一點。
trait GroupUnderAddition[T] {
def + (t : T) : T
}
case class Real(d : Double) extends GroupUnderAddition[Real] {
def + (r : Real) = Real(d + r.d)
}
case class Complex(re : Double, im : Double) extends GroupUnderAddition[Complex] {
def + (c : Complex) = Complex(re + c.re, im + c.im)
}
object Test {
implicit def real_to_complex(r : Real) = Complex(r.d, 0)
def test[G <: GroupUnderAddition[G]](a : G, b : G) = a + b
def main(args : Array[String]) {
println(test(Real(5), Real(2)))
}
}
現在,我怎麼能寫測試(),使
test(Real(5), Complex(2, 1))
收益複合物(7,1)?
當然,我能做到這一點,但我想保持仿製藥。做你的方式,如果我想叫測試與兩個多項式,我需要重寫整個事情。 – 2012-02-12 12:14:20
是的,但你有2個不同的問題,第一個是要創建通用'GroupUnderAddition'這將實現方法'+'。在另一方面,你想有一個特定的'GroupUnderAddition'實現2種不同的數字:'Real'和'Complex'。所以,你必須到另一個絕招,這就是爲什麼你想過'隱def'但在你的情況我沒有找到這個解決方案。 – 2012-02-12 13:43:48