Scala - 隐式转换为隐式参数

标签 scala

我有一个类 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/

相关文章:

scala - Spark : Convert column of string to an array

java - 在 Java 8 中展开多个可选变量

scala - 从 Tika LanguageIdentifier 转移到 Tika LanguageDetector

scala - Play 框架 2.6 CSRF 和 session

scala - Play : Bind a form field to a double?

json - 如何在spark scala中将json字符串解析到不同的列?

scala - 函数的仿函数语法 `map` 不起作用?

java - 可重入锁在 Java 中工作正常,但在 Scala 中导致 IllegalMonitorException

scala - 处理 Akka actor 中的错误

java - 如何关闭 Netty 库调试输出?