class Foo[T](t: T)(implicit int: Numeric[T]) {
val negated = -t
val doubled = t + t
val squared = t * t
// ...
}
I get red squigglies on all three lines here. What gives?
You have an instance of Numeric[T]
for some T
, and this is where all the goodies are. So you simply need to access your desired methods (e.g. plus
):
class Foo[T](t: T)(implicit int: Numeric[T]) {
val sum = int.plus(t, t)
}
If you use a context bound (the "T : Numeric" syntactic sugar), then:
class Foo[T : Numeric](t: T) {
val sum = implicitly[Numeric[T]].plus(t, t)
}
If you want to use the shortcut operators such as +
, you can simply import the members of your implicit instance:
class Foo[T](t: T)(implicit int: Numeric[T]) {
import int._
val sum = t + t
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With