2

The book "Programming in Scala" specifies:

Up through Scala 2.7, that was the end of the story. Whenever multiple implicit conversions applied, the compiler refused to choose between them. ... Scala 2.8 loosens this rule. If one of the available conversions is strictly more specific than the others, then the compiler will choose the more specific one. ... one implicit conversion is more specific than another if one of the following applies:

• The argument type of the former is a subtype of the latter’s.

Consider the following case:

object Encoder {
  implicit def fromInt(x: => Int) = { println("int"); new Encoder }
  implicit def fromIntArray(x: => Array[Int]) = { println("int array"); new Encoder }
  implicit def fromGenericArray[T](x: => Array[T])(implicit subencoder: (=> T) => Encoder) = {
    println("generic array")
    subencoder(x(0))
    new Encoder
  }
}
val e: Encoder = Array(1)

Multiple conversions can apply here, but it seems that fromIntArray is picked up. When fromIntArray is not present, fromGenericArray is chosen. My question is, is this specific case where the rule above applies so that can I safely expect that fromIntArray would apply for Array[Int] and fromGenericArray for all other Array[T]'s?

2
  • 1
    I would say yes, but read the Scala language specification, it goes to great lengths to explain implicit conflict resolution :-) Commented Mar 25, 2013 at 8:24
  • Looks like I'll have to. Thanks for the suggestion :) Commented Mar 26, 2013 at 9:47

1 Answer 1

1

From the Scala language specification:

If there are several eligible arguments which match the implicit parameter’s type, a most specific one will be chosen using the rules of static overloading resolution (§6.26.3). If the parameter has a default argument and no implicit argument can be found the default argument is used.

http://www.scala-lang.org/docu/files/ScalaReference.pdf

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.