1

How does scala.math.BigDecimal is implicitly converted to scala.math.Numeric?

For example: for Int chain of implicit conversion is traced like: Int to RichInt (conversion defined in Predef) and method

protected implicit def num: Numeric[T]

from parent class scala.runtime.ScalaNumberProxy.

The tricky part with scala.math.BigDecimal is that it does not have any wrappers.

Thanks in advance.

tkachuko
  • 1,864
  • 12
  • 19

1 Answers1

2

Numeric[T] is a type class, so it doesn't convert the BigDecimal to a Numeric; instead, there is an implicit Numeric[BigDecimal] defined which contains the implementation of Numeric which operates on BigDecimal values.

The implicit is defined here - https://github.com/scala/scala/blob/2.12.x/src/library/scala/math/Numeric.scala#L187

pyrospade
  • 7,124
  • 1
  • 32
  • 50
  • How does this implicit appears to be in `Predef`? I do not need to import anything from `scala.math` for this implicit to work. Please elaborate. – tkachuko May 01 '17 at 01:38
  • Good question. The implicit instance exists in the companion object for Numeric, which is one of the places scala looks for implicit values. It will check the companion for the implicit type (Numeric) and its type parameters (BigDecimal), and the current scope. You'll want to read up on where scala looks for implicits to better understand this - http://stackoverflow.com/questions/5598085/where-does-scala-look-for-implicits – pyrospade May 01 '17 at 01:45
  • As such, when defining your own implicits (or better yet, type class instances) try to keep them in the associated companion object. – pyrospade May 01 '17 at 01:46
  • Thanks a lot, now it makes total sense :) – tkachuko May 01 '17 at 01:52