Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about Scala implicit conversions Non-Ambiguity Rule

Could anybody explain me following situation with Scala implicit conversions mechanism. There is a code:

object Main {
  implicit val x:Int => String = v => "val"
  implicit def y(v:Int) = "def"

  def p(s:String) = print(s)

  def main(args: Array[String]): Unit = {
      p(1)
  }
}

This code prints "val". But when I comment second line:

//implicit val x:Int => String = v => "val"

code prints "def".

So both implicit conversions (x and y) are possible in this situation. There is a Non-Ambiguity Rule - an implicit conversion is only inserted if there is no other possible conversion to insert. According to this rule this code shouldn't be compiled at all. But the code is successfully compiled and executed. What I don't understand?

Thanks.

like image 428
Artem Bergkamp Avatar asked Oct 18 '10 19:10

Artem Bergkamp


People also ask

How do you use implicit conversions?

An implicit conversion from type S to type T is defined by an implicit value which has function type S => T , or by an implicit method convertible to a value of that type. Implicit conversions are applied in two situations: If an expression e is of type S , and S does not conform to the expression's expected type T .

What is implicit conversion in Scala?

Implicit conversions in Scala are the set of methods that are apply when an object of wrong type is used. It allows the compiler to automatically convert of one type to another. Implicit conversions are applied in two conditions: First, if an expression of type A and S does not match to the expected expression type B.


1 Answers

The reason for this is stated in the Scala Language Specification section 6.26.2.

Before the method can be treated as a function it needs to be converted to one by performing eta-expansion. Thus one more implicit conversion would have to be applied and so the val is chosen.

UPDATE: removed flawed example.

Evaluation of a method without parameters is always performed implicitly.

like image 196
Moritz Avatar answered Oct 07 '22 16:10

Moritz