我有一个类 A
,它还定义了到 B
的隐式转换。
case class A(number:Int)
case class B(number:Int, tag:String)
implicit def AtoB(a:A) = B(a.number,"Hello World")
我还有一个检索 A
的函数,并希望调用一个以隐式 B
作为参数的函数:
def hello()(implicit b:B)= {....}
def execute = {
implicit val a:A = ....
hello() //doesnt compile missing implicit parameter b
}
如何在不显式定义 B
的情况下使此代码正常工作?即
val b:B = a
最佳答案
定义一个这样的函数:
implicit def implicitBfromA(implicit a: A): B = a
并且可以在调用 hello
时将其置于作用域内,或者将其放入 B
的伴生对象中。
此函数不是隐式转换。它指出,如果范围内已经存在可用的 A
类型的隐式值,则存在可用的 B
类型的隐式值。
请注意,要使其正常工作,它应该在文件中的 AtoB
之后定义,或者 AtoB
应该有一个明确指定的返回类型:隐式 def AtoB(a:A): B = B(a.number, "Hello World")
,或者您应该在其主体中显式调用 AtoB
: 隐式 defimplicitBfromA(隐式 a: A): B = AtoB(a)
完整的工作示例:
case class A(number: Int)
case class B(number: Int, tag: String)
object B {
implicit def implicitB(implicit a: A): B = a
}
implicit def AtoB(a:A): B = B(a.number, "Hello World")
def hello()(implicit b: B) = b.number.toString + b.tag
def execute = {
implicit val a: A = A(10)
hello()
}
关于Scala - 隐式转换为隐式参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35701451/