选择最具体的子类型的隐式解析

Implicit resolution choosing the most specific subtype

有人可以解释一下为什么 scala 解析最通用的隐式,而不管局部范围隐式更具体吗?

示例:

import scala.math.ScalaNumber

type Serializer[T] = T => String

object SerializedOps{
  implicit class AnyOps[T](t: T){
    def serialize(implicit s: Serializer[T]) : String = s(t)
  }
}

object Instances{
  implicit val scalaNumber : Serializer[ScalaNumber] = _.toString + "_DEFAULT"
}


import SerializedOps._
import Instances._


implicit val bigDecimalCustom : Serializer[BigDecimal] = _.toString + "_CUSTOM"

val res: String = BigDecimal(100).serialize
//res: String = 100DEFAULT

为什么我不能在本地范围内定义更具体的新隐式? Scala 如何解析隐式?

:

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.

但是函数 contravariant 超过了它的参数类型,这使得

ScalaNumber => String

的子类型
BigDecimal => String

因此 ScalaNumber => String 更具体。请注意,type Serializer[T] = T => String 是函数类型的别名。