# Implicit Parameter Resolution

This topic is a continuation of the previous implicit parameter topics:

This topic provides some explanation about how implicit parameters are resulted. There are very strict rules for which implicit value is to be applied to a implicit parameter. A simple way to think about it is that the “closest” definition will be used. Local scope, enclosing class, parent class, companion object of the desired type.
``` ```

``` class X(val i:Int) class Y(val i:Int) object X {   implicit def xx = new X(1) } class Method {   def x(implicit x:X)=println(x.i)   def y(implicit y:Y)=println(y.i) } trait M {    self : Method =>   implicit def x1 = new X(10)   implicit def y1 = new Y(100)   def testy = y   def testx = x } trait SM extends M {   self : Method =>   implicit def x2 = new X(20)   implicit def y2 = new Y(200)      def testy2 = y   } // implicit resolved from companion object of X new Method().x // explicit applied so that value is used new Method().x(new X(3)) // implicit resolved from companion object of X // NOT from M.  This is because the call site of x  // is not within M therefore does not use the implicits in M // for resolution. (new Method with M).x implicit def x = new X(30) // local scope overrides companion object implicit new Method().x // explicit applied so that value is used new Method().x(new X(3)) // local scope overrides companion object implicit (new Method with M).x // testy is defined within M so the implicits within M (new Method with M).testy // testx is defined within M so the implicit within M // overrides the companion object implicit (new Method with M).testx // testy is within M (not SM) so the implicit within M // is used (new Method with SM).testy // testy2 is within SM so the implicit within SM  // overrides the implicit in M and the companion object (new Method with SM).testy2 ```
``` ```

Output:

1
3
1
30
3
30
100
10
100
200
Continua a leggere

Pubblicato in Senza categoria

# Implicit Parameters

Evidently the topic of implicit parameters has not yet been correctly addressed. There have been several topic that refer to implicit parameters but none that directly discuss them. So before I continue with the topic of implicit parameter resolution I will discuss implicit parameters.

First, implicit parameters are not the same as implicit object conversions. Implicit parameters provide a way to allow parameters of a method to be “found”. This is similar to default parameters at a glance but in fact is a different mechanism for finding the “default” value. It differs from implicit object conversion in that it is only a way for parameters for a method to be resolved. Implicit object conversion allows methods to appear to be called on one object when in fact that object is being converted behind the scenes to another type. (more or less)

An implicit parameter is a parameter to method or constructor that is marked as implicit. This means that if a parameter value is not supplied then the compiler will search for an “implicit” value defined within scope (according to resolution rules.) Implicit parameter resolution rules will be discussed soon.

Example:
``` ```

``` scala> def p(implicit i:Int) = print(i) p: (implicit i: Int)Unit // defining a val/var/def as implicit  // means that it will be considered during implicit resolution scala> implicit val v=2 v: Int = 2 // scope is searched for a implicit value to sue // v is found as marked implicit scala> p                2 // explicit declarations always overrides implicit values scala> p(1) 1 ```
``` ```

Implicit parameters are very nice for simplifying APIs. For example the collections use implicit parameters to supply CanBuildFrom objects for many of the collection methods. This is because normally the user does not need to be concerned with those parameters. Another example is supplying an encoding to an IO library so the encoding is defined once (perhaps in a package object) and all methods can use the same encoding without having to define it for every method call.

One important restriction is that there can only be a single implicit keyword per method. It must be at the start of a parameter list (which also makes all values of that parameter list be implicit). I further understand that only the last parameter list may be implicit.

Here are several illegal examples:
``` ```

``` // implicit is not in last parameter list scala> def pp(implicit i:Int, a:Int)(b:Int) = println(a,i)                  < console>:1: error: '=' expected but '(' found.        def pp(implicit i:Int, a:Int)(b:Int) = println(a,i) // there are 2 implicit parameters scala> def pp(implicit j:Int, a:Int)(implicit i:Int,b:Int) = println(a,i) < console>:1: error: '=' expected but '(' found.       def pp(implicit j:Int, a:Int)(implicit i:Int,b:Int) = println(a,i) // implicit is not the first parameter of the parameter list scala> def pp(a:Int, implicit i:Int) = println(i,j)          < console>:1: error: identifier expected but 'implicit' found.        def pp(a:Int, implicit i:Int) = println(i,j)                      ^ ```
``` ```

Here are several legal examples (Updated with useage examples):
``` ```

``` scala> implicit def v = 7 v: Int scala> implicit var x = 10L x: Long // i is implicit scala> def pp(a:Int)(implicit i:Int) = println(a,i) pp: (a: Int)(implicit i: Int)Unit scala> pp(3) (3,7) // both i and b are implicit scala> def pp(a:Int)(implicit i:Int, b:Long) = println(a,i,b)  pp: (a: Int)(implicit i: Int,implicit b: Long)Unit scala> pp(4)                (4,7,10) // both i and b are implicit scala> def pp(implicit i:Int, b:Long) = println(i,b)   pp: (implicit i: Int,implicit b: Long)Unit scala> pp (7,10) // all or none of the parameters must be supplied scala> pp(2) < console>:13: error: not enough arguments for method pp: (implicit i: Int,implicit b: Long)Unit. Unspecified value parameter b.        pp(2) // This is syntactically legal but I cannot seem to implicitly invoke this // I would recommend: def pp(b:Long*)(implicit i:Int) = println(i,b) scala> def pp(implicit i:Int, b:Long*) = println(i,b) pp: (implicit i: Int,implicit b: Long*)Unit scala> pp(3,1,2,3) (3,WrappedArray(1, 2, 3)) scala> def pp(b:Long*)(implicit i:Int) = println(i,b) pp: (b: Long*)(implicit i: Int)Unit scala> pp(1,2,3) (7,WrappedArray(1, 2, 3)) ```
``` ```

A related topic is Companion Object implicits. Continua a leggere

Pubblicato in Senza categoria

# Break Performance

In the Breaks comments there were several questions about the performance of the Scala break command vs the Java break command. So I decided to take a look.

The code for the tests is available on GitHub at: Scala Benchmarks. Feel free to play around with it.

I personally don’t think these tests say anything of particular import because they only test how fast the Java break is vs the Scala break without doing any work in the loop. So I don’t expect these number would ever been seen in the real world. However that said if you have a tight loop with minimal processing then a Scala break may not be the correct construct to use.

Here is the Java test (labelled JavaSimpleBreak)
``` ```

``` int i = 0; while (i < 10) {   if(i==1) break;   i += 1; } ```
``` ```

Here is the Scala test (labelled ScalaSimpleBreak)
``` ```

``` var i = 0; breakable {   while (i < 10) {     if(i==1) break;     i += 1;   } } ```
``` ```

Out of curiosity I also added a test that created a new Exception each iteration (labelled ScalaException):
``` ```

``` var i = 0;   while (i < 10) {     if(i==1) throw new Exception();     i += 1;   } ```
``` ```

And also a test that just throws the same ScalaBreak exception each time. This one is weird since Scala Simple Break also throws the same exception but is much much faster so I think there is something about popping the stack in the example compared to the ScalaSimpleBreak test.
``` ```

``` var i = 0; breakable { while (i < 10) { if(i==1) break; i += 1; } } ```
``` ```

The results of the tests:

First, don’t compare the break tests to the Exception tests. They are sufficiently different to not be worth comparing.
Second, remember that this is a micro benchmark and has very little relationship to reality.

90000000 iterations. Swapping every 90000000 tests
JavaSimpleBreak = 254 (0.0016279129387033098)
ScalaSimpleBreak = 2475 (0.015862537493270438)
ScalaBreakException = 18806 (0.12052964852462379)
ScalaException = 156028 (1.0)

90000000 iterations. Swapping every 500000 tests
JavaSimpleBreak = 772 (0.005138547761203965)
ScalaSimpleBreak = 2351 (0.015648608531853004)
ScalaBreakException = 19346 (0.12876987692778744)
ScalaException = 150237 (1.0)

90000000 iterations. Swapping every 500 tests
JavaSimpleBreak = 790 (0.005242446563543097)
ScalaSimpleBreak = 2247 (0.014911110668710557)
ScalaBreakException = 19213 (0.1274976276270298)
ScalaException = 150693 (1.0)
Continua a leggere

Pubblicato in Senza categoria

# Companion Object Implicits

When a method requires an implicit there are several ways that the implicit is resolved. One way is to search for an implicit definition in the companion object of the required type. For example: `def x(implicit m:MyClass)` parameter m will search local scope, class hierarchy and the MyClass companion object for an implicit val or def. (More on implicit resolution later).

To demonstrate the method put the following code block into a file and run the script:
``` ```

``` class X(val i:Int) {   def add(implicit x:X)=println(x.i+i) } object X {   implicit def xx = new X(3) } // implicit is obtained from companion object of X new X(3).add val other = new {   def print(implicit x:X)=println(x.i) } // implicit is obtained from companion object of X other.print implicit def x = new X(32) // implicit is obtained local scope other.print ```
``` ```

Running: scala impl.scala should produce:
6
3
32 Continua a leggere

Pubblicato in Senza categoria

# Breaks

Scala 2.8 added the break control flow option. It is not implemented as a special language feature. Rather it is simply implemented as an object/trait using standard Scala mechanisms. If you are interested in creating a control flow object similar to this look at the Defining Custom Control Structures post.

The Break functionality is works basically how you would expect:
``` ```

``` // Import the control flow methodsmethods scala> import util.control.Breaks._ import util.control.Breaks._ // pass a function to the breakable method scala> breakable {      | for (i <- 1 to 10 ) {      | if(i > 5) break  // call break when done      | println(i)      | }      | } 1 2 3 4 5 ```
``` ```

Pretty intuitive but beware, break only breaks out to the first enclosing breakable. Here is an example of the issue:
``` ```

``` scala> def loop(f : Int => Boolean) = breakable {      | for (i <- 1 to 300) if (f(i)) break else println(i)      | } loop: (f: (Int) => Boolean)Unit // This never ends because break is caught by breakable in the loop method scala> breakable {      | while(true) {      | loop{ i => break; true }      | }      | } ```
``` ```

Fortunately the implementers provide an elegant way to handle these sorts of cases. The Breaks object extends the Breaks class. By instantiating other instances of Breaks it is possible to control which breaks capture
``` ```

``` scala> import scala.util.control._ import scala.util.control._ scala>  scala> def loop(f : Int => Boolean) = {      |   val Inner = new Breaks      |   Inner.breakable {      |     for (i <- 1 to 4) if (f(i)) Inner.break else println(i)      |   }      | } loop: (f: (Int) => Boolean)Unit scala>  scala> val Outer = new Breaks Outer: scala.util.control.Breaks = scala.util.control.Breaks@1ba4806 scala> Outer.breakable {      |   while(true) {      |     loop{ i => if(i==4) Outer.break; false}      |   }      | } 1 2 3 ```
``` ```
Pubblicato in Senza categoria

# Scala 2.8 Arrays are not Traversables

One performance/consistency change that has been make in Scala 2.8 is to make Scala Array always be a Java Array. This has some consequences which we will examine in this post. The biggest one is that Array is not a Scala Collection/Traversable. It is implicitly converted to one but it is not an instance of a Traversable. There are several reasons this was done. Probably the biggest is for performance. Because a Scala array is a Java array there is no overhead when using a Scala array.

Thanks to implicit type conversion all the normal collection methods are useable with an array. Even better, after running a method like map the result will again be a Java array. So the API is much more consistent.

An example illustrating that an Array is not a Traversable:
``` ```

``` // This does not compile (which is good)  // because Traversable[Int] can never be an array scala> def x(t:Traversable[Int]) = t match {      | case x : Array[Int] => true                | } < console>:13: error: pattern type is incompatible with expected type;  found   : Array[Int]  required: Traversable[Int]        case x : Array[Int] => true                 ^ < console>:13: error: type mismatch;  found   : Array[Int]  required: Traversable[Int]        case x : Array[Int] => true               ^ ```
``` ```

Another example:
``` ```

``` scala> def x(t:Traversable[Int]) = t.isInstanceOf[Array[_]] x: (t: Traversable[Int])Boolean /* this evaluates to false because Array is converted  * to WrappedArray because it has to be implicitly converted  * to a Traversable.  Since Array is not a Traversable the resulting   * object is not an Array  */ scala> x(Array(1,2,3))                                      res24: Boolean = false scala> def x(t:Traversable[Int]) = println(t) x: (t: Traversable[Int])Unit // This method call demonstrates the previous assertion scala> x(Array(1,2,3))                                             WrappedArray(1, 2, 3) ```
``` ```

So suppose you want to be able to accept and use arrays and Traversables in a method but you want to be able to
check that the parameter is an Array. Why not match against WrappedArray. You probably can, but you may get performance improvements in some cases if you don’t require wrapping the array.

For a more concrete example of why you may want to do this. In a Input/Output routine I wrote I would write the data one way if the input was an Array: `stream.write(array)`. But if the input was a traversable then I would have to handle it differently. My particular issue was more complicated than that but that is the basic issue.

So the work around is to define a Generic parameter for the method:
``` ```

``` scala> def x[T <% Traversable[Int]](t:T) = t match {       | case x : Array[Int] => true                                      | } x: [T](t: T)(implicit evidence\$1: (T) => Traversable[Int])Boolean scala> x(Array(1,2,3))                                res27: Boolean = true ```
``` ```
Pubblicato in Senza categoria

# Daily scala 2010-04-16 08:56:00

A quick note. ScalaDays Rocks! Wish you were here

This topic just demonstrates a cute little trick that can occasionally be quite useful:
``` ```

``` scala> List(1,2,3) ++ Some(4) res0: List[Int] = List(1, 2, 3, 4) scala> List(1,2,3) ++ None    res1: List[Int] = List(1, 2, 3) ```
``` ```

Options are implicitly converted to Iterables, so Options can be appended to collections.
``` ```

``` scala> val x : Iterable[Int] = None        x: Iterable[Int] = List() scala> val x : Iterable[Int] = Some(4) x: Iterable[Int] = List(4) ```
``` ```
Pubblicato in Senza categoria