I had a strange bug yesterday that I eventually reduced to the following code:
Welcome to Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_29).
Type in expressions to have them evaluated.
Type :help for more information.
scala> class X extends Function[String, Int] { def apply(x: String) = Integer.parseInt(x) }
defined class X
scala> implicit val x = new X
x: X = <function1>
scala> "56" / 2
res2: Int = 28
I expect this to throw an exception, since String doesn't have a /
method. Instead, Scala treated the implicit variable as an implicit method (because it implements Function[String,Int]
) and converted the string "56" to the integer 56.
How does this work? Based on the rules of implicit search, I didn't think implicit variables that act as functions would be considered.
The semantics of implicit conversions are exactly what you've observed. If you define an implicit conversion via an implicit method,
trait A
trait B
implicit def aToB(a : A) : B = new B {}
you'll see that you now have an implicit function value A => B
,
scala> implicitly[A => B]
res1: A => B = <function1>
And where you have a method with a view bound,
def foo[T <% B](t : T) : B = t
this is equivalent to,
def foo[T](t : T)(implicit conv : T => B) : B = conv(t)
ie. the implicit argument corresponding to a view bound is of exactly the same form as the implicit function value produced by an implicit method definition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With