gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:06:11 25 4
gpt4 key购买 nike

我在 Scala 中创建伴生对象并尝试在 class 中使用 object 隐式函数而不导入。但是每当尝试编译代码时,我都会收到一个错误:type mismatch; seems it is not able to import implictis automatically。以下是我的代码:

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")
}
}

当我在类里面使用 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 类相关的隐式的地方。这会强制您显式导入包含这些隐式的对象。相反,做:

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:在伴随对象中使用隐式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41185067/

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