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
Speaking of which, why does the following not work?
ReplyDeleteclass A(i: Int)
object A {implicit def int2A(i: Int) = new A(i) }
val a: A = 2
The implicit conversion is defined in the companion object of the expected type. Which part do I not get?
It does of course work if I "import A._", but I'm still looking for a way around that.
You are confusing implicit parameter resolution with implicit object conversion. Implicit object conversion is potentially dangerous so they normally have to be imported explicitly into scope.
ReplyDeleteCaveats to that is implicit object conversions defined in superclasses and (I am pretty sure) in package objects are automatically in scope.
I will address this soon.
Dear Jesse,
ReplyDeleteI put the implicit conversion into a package object now and that indeed did the trick. Thanks for the hint!