Unexpected behavior with implications

I had a strange error yesterday that I ended up boiling down 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 does not 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 it works? Based on the implicit search rules, I did not think that implicit variables that act as functions would be considered.

+6
source share
1 answer

The semantics of implicit transformations are exactly what you observed. If you define an implicit conversion through an implicit method,

 trait A trait B implicit def aToB(a : A) : B = new B {} 

you will see that now you have an implicit function value A => B ,

 scala> implicitly[A => B] res1: A => B = <function1> 

And where do you have a view-bound method,

 def foo[T <% B](t : T) : B = t 

it is equivalent

 def foo[T](t : T)(implicit conv : T => B) : B = conv(t) 

i.e., the implicit argument corresponding to the estimate has exactly the same form as the value of the implicit function created using the implicit method definition.

+7
source

Source: https://habr.com/ru/post/910194/


All Articles