0

I am getting some (what seems to me) strange behavior when using the + method in a generic case class (below). The bottom method works fine, but the top one gives me an error for addVal - type mismatch; found: DataT, required: String.

I assume what is going on here is the compiler has converted this.datum into a String and so wants to use the String.plus method, whereas I want it to use the Numeric.plus method. Normally it would default to using the Numeric.plus method when presented with two Numeric instances so I'm not quite sure why it isn't in this case.

case class SingleValue[DataT <: Numeric[DataT]] ( datum: DataT, ) { def addToDatumDoesntWork(addVal: DataT): SingleValue[DataT] = SingleValue[DataT](this.datum + addVal) def addToDatumWorks(addVal: DataT): SingleValue[DataT] = SingleValue[DataT](this.datum.plus(this.datum, addVal)) } 

1 Answer 1

3

You're not invoking the Numeric type class the way it was intended.

case class SingleValue[DataT : Numeric](datum: DataT) { import Numeric.Implicits._ def addToDatumNowItWorks(addVal: DataT): SingleValue[DataT] = SingleValue[DataT](this.datum + addVal) } 

It can also be done this way. (The two are roughly equivalent.)

case class SngleValue[DataT](datum: DataT)(implicit ev :Numeric[DataT]) { import ev._ def addToDatumNowItWorks(addVal: DataT): SingleValue[DataT] = SingleValue[DataT](this.datum + addVal) // or def addToDatumWorks(addVal: DataT): SingleValue[DataT] = SingleValue[DataT](ev.plus(this.datum, addVal)) } 

The idea is that you pull in the "evidence" that the proper implicit exists, then you can import what's needed for the infix notation.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you. I had not really thought about the distinction between SingleValue[DataT <: Numeric[DataT]] and SingleValue[DataT: Numeric] before. This question is actually part of a larger (though still not very large) issue I have been having for the past day or so - I have posted it here: stackoverflow.com/questions/63628278/… You seem to know your way round this topic well so if you could lend a hand there then I would be most grateful.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.