Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behavior with implicits

Tags:

scala

implicit

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.

like image 238
Bill Avatar asked Mar 07 '12 17:03

Bill


1 Answers

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.

like image 54
Miles Sabin Avatar answered Sep 30 '22 12:09

Miles Sabin