2014-11-01 57 views
2

我有兩個基本相同的案例類,除了一個有Int和其他Double成員。我試圖創建一個通用特徵,我可以使用它們來運行函數,並允許基本的數字操作。但到目前爲止,我無法弄清楚如何使用無論是數字或行動類型:scala類型簽名允許成員上的數字操作

trait Sentiment[A] { 
    def positive: A 
    def negative: A 
} 

case class IntSentiment(positive: Int, negative: Int) extends Sentiment[Int] 

我想拿出一個函數的約束,這樣我可以在該部件上進行數字OPS,沿東西行:

def effective[A](sentiment: Sentiment[A]): A = { 
    sentiment.positive - sentiment.negative 
} 

這不工作,我想我需要以某種方式調用Numeric類型的類,但我來最接近的是:

def effective[A](sentiment: Sentiment[A])(implicit num: Numeric[A]): A = { 
    num.minus(sentiment.positive,sentiment.negative) 
} 

是否有型約束/簽名Sentiment和/或effective我可以定義實際上只是直接在成員上使用+- ops?

+2

順便說一句,在普通的斯卡拉泛型數值是盒裝的,所以不是那麼快。你可能不需要他們。如果你這樣做,看看Spire。 – 2014-11-01 21:17:46

+0

尖頂看起來很有趣。感謝指針 – 2014-11-01 21:55:19

回答

4
import scala.Numeric.Implicits._ 

def effective[A : Numeric](sentiment: Sentiment[A]): A = { 
    sentiment.positive - sentiment.negative 
}