I am trying to create a type class with multiple type parameters. I am trying to invoke the method implicitly based on the types
I am showing a simple snippet of the code I have tried.
object operation {
// Define generic trait class
trait Operator[T, U] {
def addition[T, U](l: U, r: T)(implicit p: Parameters): U
}
object Operator {
// Define type class.
implicit object IntOperator extends Operator[Int, Float] {
def addition(l: Int, r: Float): Float = {
r
}
}
}
// Create mapping for implicit call.
def addition[T, U](l: T, r: U)(implicit op: Operator[T, U]): U = op.addition(l, r,)
}
import operation._
def fn(a: UInt, b: Float)
addition(a,b)
If I use a single type parameter i.e., only [T,U] then this code compiles fine. However If I use two type parameters i.e., Operator[T,U] then the addition(a,b) complains No implicits found for parameter Operator[T,U]. Any help would be appreciated.
I hope the simplified code snippet elaborates on what I am trying to do.
Parametersdefined, why didn't you used it on yourIntOperator, why are you re declaringTandUin addition on the trait?, was that a typo? Is the last addition call being done insidefn, if not from where didaandbcame from?UIntfrom thespire.mathlibrary? If so, the problem seems to be that implicit resolution for value classes doesn't use resolution for the underlying type. (I also had trouble getting your code to compile - you definitely need to remove the type parameters fromdef additionand correct the return type forIntOperatorto even be recognised as a valid implementation.)