3

I have two case classes that are basically identical, except that one has Int and the other Double members. I'm trying to create a common trait that I can use for functions operating on either and allowing basic numeric operations. But so far i can't figure out how to use either the Numeric or Ops types:

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

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

I would like to come up with a function constraint so that I can perform numeric ops on the members, something along the lines of:

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

This does not work, and I figure i need to invoke the Numeric type class somehow, but the closest I've come is:

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

Is there a type constraint/signature on Sentiment and/or effective I can define to actually just use + and - ops on the members directly?

Arne Claassen
  • 14,088
  • 5
  • 67
  • 106

1 Answers1

6
import scala.Numeric.Implicits._

def effective[A : Numeric](sentiment: Sentiment[A]): A = {
  sentiment.positive - sentiment.negative
}
Lee
  • 142,018
  • 20
  • 234
  • 287