gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:42:23 24 4
gpt4 key购买 nike

有人能解释一下为什么 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 如何解析隐式?

最佳答案

Subtype does win :

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 是函数类型的别名。

关于scala - 选择最具体的子类型的隐式解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56892483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com