The following example from A Tour of Scala shows how implicit can be used to provide the appropriate missing members (add and unit) based on the type. The compiler will pick the right implicit object in scope. The library also uses that with List.sortBy
and Ordering
or List.sum
and Numeric
for instance.
However is the following usage in class B a valid/recommended usage of implicit parameters (as opposed to not 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 the implicit to save myself some typing at the call site when passing a parameter along the stack.