I have read the answer to my question about scala.math.Integral but I do not understand what happens when Integral[T]
is passed as an implicit parameter. (I think I understand the implicit parameters concept in general).
Let's consider this function
import scala.math._
def foo[T](t: T)(implicit integral: Integral[T]) { println(integral) }
Now I call foo
in REPL:
scala> foo(0)
scala.math.Numeric$IntIsIntegral$@581ea2
scala> foo(0L)
scala.math.Numeric$LongIsIntegral$@17fe89
How does the integral
argument become scala.math.Numeric$IntIsIntegral
and scala.math.Numeric$LongIsIntegral
?
The short answer is that Scala finds
IntIsIntegral
andLongIsIntegral
inside the objectNumeric
, which is the companion object of the classNumeric
, which is a super class ofIntegral
.Read on for the long answer.
Types of Implicits
Implicits in Scala refers to either a value that can be passed "automatically", so to speak, or a conversion from one type to another that is made automatically.
Implicit Conversion
Speaking very briefly about the latter type, if one calls a method
m
on an objecto
of a classC
, and that class does not support methodm
, then Scala will look for an implicit conversion fromC
to something that does supportm
. A simple example would be the methodmap
onString
:String
does not support the methodmap
, butStringOps
does, and there's an implicit conversion fromString
toStringOps
available (seeimplicit def augmentString
onPredef
).Implicit Parameters
The other kind of implicit is the implicit parameter. These are passed to method calls like any other parameter, but the compiler tries to fill them in automatically. If it can't, it will complain. One can pass these parameters explicitly, which is how one uses
breakOut
, for example (see question aboutbreakOut
, on a day you are feeling up for a challenge).In this case, one has to declare the need for an implicit, such as the
foo
method declaration:View Bounds
There's one situation where an implicit is both an implicit conversion and an implicit parameter. For example:
The method
getIndex
can receive any object, as long as there is an implicit conversion available from its class toSeq[T]
. Because of that, I can pass aString
togetIndex
, and it will work.Behind the scenes, the compile changes
seq.IndexOf(value)
toconv(seq).indexOf(value)
.This is so useful that there is a syntactic sugar to write them. Using this syntactic sugar,
getIndex
can be defined like this:This syntactic sugar is described as a view bound, akin to an upper bound (
CC <: Seq[Int]
) or a lower bound (T >: Null
).Please be aware that view bounds are deprecated from 2.11, you should avoid them.
Context Bounds
Another common pattern in implicit parameters is the type class pattern. This pattern enables the provision of common interfaces to classes which did not declare them. It can both serve as a bridge pattern -- gaining separation of concerns -- and as an adapter pattern.
The
Integral
class you mentioned is a classic example of type class pattern. Another example on Scala's standard library isOrdering
. There's a library that makes heavy use of this pattern, called Scalaz.This is an example of its use:
There is also a syntactic sugar for it, called a context bound, which is made less useful by the need to refer to the implicit. A straight conversion of that method looks like this:
Context bounds are more useful when you just need to pass them to other methods that use them. For example, the method
sorted
onSeq
needs an implicitOrdering
. To create a methodreverseSort
, one could write:Because
Ordering[T]
was implicitly passed toreverseSort
, it can then pass it implicitly tosorted
.Where do Implicits Come From?
When the compiler sees the need for an implicit, either because you are calling a method which does not exist on the object's class, or because you are calling a method that requires an implicit parameter, it will search for an implicit that will fit the need.
This search obey certain rules that define which implicits are visible and which are not. The following table showing where the compiler will search for implicits was taken from an excellent presentation about implicits by Josh Suereth, which I heartily recommend to anyone wanting to improve their Scala knowledge.
Let's give examples for them.
Implicits Defined in Current Scope
Explicit Imports
Wildcard Imports
Same Scope in Other Files
This is like the first example, but assuming the implicit definition is in a different file than its usage. See also how package objects might be used in to bring in implicits.
Companion Objects of a Type
There are two object companions of note here. First, the object companion of the "source" type is looked into. For instance, inside the object
Option
there is an implicit conversion toIterable
, so one can callIterable
methods onOption
, or passOption
to something expecting anIterable
. For example:That expression is translated by the compile into
However,
List.flatMap
expects aTraversableOnce
, whichOption
is not. The compiler then looks insideOption
's object companion and finds the conversion toIterable
, which is aTraversableOnce
, making this expression correct.Second, the companion object of the expected type:
The method
sorted
takes an implicitOrdering
. In this case, it looks inside the objectOrdering
, companion to the classOrdering
, and finds an implicitOrdering[Int]
there.Note that companion objects of super classes are also looked into. For example:
This is how Scala found the implicit
Numeric[Int]
andNumeric[Long]
in your question, by the way, as they are found insideNumeric
, notIntegral
.Companion Objects of Type Parameters Types
This is required to make the type class pattern really work. Consider
Ordering
, for instance... it comes with some implicits in its companion object, but you can't add stuff to it. So how can you make anOrdering
for your own class that is automatically found?Let's start with the implementation:
So, consider what happens when you call
As we saw, the method
sorted
expects anOrdering[A]
(actually, it expects anOrdering[B]
, whereB >: A
). There isn't any such thing insideOrdering
, and there is no "source" type on which to look. Obviously, it is finding it insideA
, which is a type parameter ofOrdering
.This is also how various collection methods expecting
CanBuildFrom
work: the implicits are found inside companion objects to the type parameters ofCanBuildFrom
.Outer Objects for Nested Types
I haven't actually seen examples of this. I'd be grateful if someone could share one. The principle is simple:
Other Dimensions
I'm pretty sure this was a joke. I hope. :-)
EDIT
Related questions of interest:
The parameter is
implicit
, which means that the Scala compiler will look if it can find an implicit object somewhere that it can automatically fill in for the parameter.When you pass in an
Int
, it's going to look for an implicit object that is anIntegral[Int]
and it finds it inscala.math.Numeric
. You can look at the source code ofscala.math.Numeric
, where you will find this:Likewise, there is a different implicit object for
Long
that works the same way.