Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: how do I access a `Numeric` type's arithmetic operations?

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?

like image 540
Carl Patenaude Poulin Avatar asked Jan 03 '23 22:01

Carl Patenaude Poulin


1 Answers

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

}
like image 184
slouc Avatar answered Jan 05 '23 11:01

slouc