开发者

Question about Scala implicit conversions Non-Ambiguity Rule

开发者 https://www.devze.com 2023-01-20 20:42 出处:网络
Could anybody explain me following situation with Scala implicit conversions mechanism. There is a code:

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 implic开发者_C百科it 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号