Actual Implicit Parameter Applications

The following example from A Tour of Scala shows how implicit can be used to provide the corresponding missing elements (add and unit) based on type. The compiler will select the correct implicit scope object. The library also uses, for example, List.sortBy and Ordering or List.sum and Numeric .

However, the following use in class B is a valid / recommended use of implicit parameters (as opposed to using implicit in class A):

 class I class A { def foo(i:I) { bar(i) } def bar(i:I) { baz(i) } def baz(i:I) { println("A baz " + i) } } (new A).foo(new I) class B { def foo(implicit i:I) { bar } def bar(implicit i:I) { baz } def baz(implicit i:I) { println("B baz " + i) } } (new B).foo(new I) 

Where I primarily use implicit to save myself some typification on the call site when passing a parameter along the stack.

+4
source share
2 answers

This is a very useful case. I really recommend this when the scope defines the parameter used. It provides an elegant way to pass some context to the Plugin class so that utility functions use context. For instance:

 trait Context object UtilityLib { def performHandyFunction(implicit x : Context) : SomeResult = ... } trait Plugin { def doYourThing(implicit ctx : Context) : Unit } class MyPlugin extends Plugin { def doYourThing(implicit ctx : Context) : Unit = { UtilityLib.performHandyFunction } } SomePluginAPI.register(new MyPlugin) 

You can see an example in the database migration system that I played in . Check the migration class and its migration context.

+3
source

Actually, this is not like the idiomatic use of implications, which are usually suitable for type classes and dependency injection. There is absolutely no point in skipping a class without members ...

Also more often to determine the implicit value of val or an object of type I before calling (new B).foo

Having said all this, you presented a clearly very abstract example. Therefore, it is not too difficult to imagine a reasonable use case for implications that follow a similar pattern.

+2
source

All Articles