Scala:在伴随对象中使用隐式

Scala: Use implicits in companion object

我正在 scala 中创建伴生对象并尝试在 class 中使用 object 隐式函数而不导入。但是每当尝试编译代码时,我都会收到 error: type mismatch; 似乎无法自动导入 implictis。以下是我的代码:

object ImplicitTest5 {
    implicit def dollarToRupa(dollar: Dollar): Rupa = { 
        println("calling .... dollarToEuro") 
        Rupa(dollar.value)
    } 

    implicit def dollarToEuro(dollar: Dollar): Euro = { 
        println("calling .... dollarToEuro") 
        Euro(dollar.value)
    } 
}

case class Dollar(value: Double)

case class Euro(value: Double)

case class Rupa(value: Double)

class ImplicitTest5 { 

    private val value = "String"

    def conversion = {
        val euro: Euro  = Dollar(3.1)
        println(s" ----- $euro")
    }
}

当我在 class 中使用 import ImplicitTest5._ 时,它会编译并且 运行 正常。根据 Programming in Scala, Page: 478 它会正常工作,不需要定义导入。

In this case, the conversion dollarToEuro is said to be associated to the type Dollar. The compiler will find such an associated conversion every time it needs to convert from an instance of type Dollar. There’s no need to import the conversion separately into your program.

我的样本出了什么问题或者我的理解有误导?

Something is going wrong with my sample or my understandings are misleading

如果您在 Dollar 的伴生对象中定义它,到 Dollar 的转换将与之相关联。目前,所有隐式都在 ImplicitTest5 上定义,这不是编译器查找与 Dollar class 相关的隐式的地方。这会强制您显式导入包含这些隐式的对象。相反,做:

case class Dollar(value: Double)
object Dollar {
  implicit def dollarToEuro(dollar: Dollar): Euro = {
    println("calling .... dollarToEuro")
    Euro(dollar.value)
  }
}

有关更多信息,请参阅 "Where does Scala look for implicits"

默认情况下,scala 编译器将查看源对象和目标对象的伴随对象。因此,例如,如果您要从 Dollor 转换为 Euro,则隐式方法可以在 Dollor 或 Euro 伴随对象中。编译器会自动选择它。否则你必须将它明确地放在范围内。