【问题标题】:what is the meaning of the implicit def function隐含的def函数是什么意思
【发布时间】:2017-05-18 20:14:10
【问题描述】:

在 scala 中,当我创建带有隐式 def 字段的 trait 时,我该如何使用它们 为什么要在 def 关键字中添加隐式关键字?

trait MyXXXProtocol extends Logging {

  implicit def actor: ActorSystem
  implicit def materializer: Materializer
  implicit def executor: ExecutionContextExecutor


}

任何例子都会有帮助。

【问题讨论】:

    标签: scala


    【解决方案1】:

    首先阅读这篇文章,它讨论了在 Scala 中在 trait 中使用 valdef 之间的区别。 here.

    当您的 trait 包含某种依赖于这些隐式的具体实现时,您将使用该模式,但您希望 trait 的最终实现者是为这些隐式指定具体值的实现者。

    trait MyXXXProtocol extends Logging {
    
      implicit def actor: ActorSystem
      implicit def materializer: Materializer
      implicit def executor: ExecutionContextExecutor
    
      def test(input: String): Unit = {
        // let's pretend this is valid
        actor.props("bla").send(input)
      }
    

    如果send 的签名是这样的,这将变得很有用:

    def send(input: String)(
      implicit system: ActorSystem,
      materializer: FlowMaterializer
    ): Unit = ...
    

    这很有用,因为您现在已经创建了一个模板,但是由具体的实现者来提供这些东西将在其中执行的隐式系统,您正在转发这些隐式,以便您可以在需要它们的地方定义一些实现,但是你可以稍后提供一个真正的隐式。

    【讨论】:

    • 正如那里的 cmets 指出的那样,您的第一段是错误的:重要的不是抽象成员是声明为 val 还是 def,而是它是否实现 作为非惰性val(或访问非惰性vals 的def)。
    • @AlexeyRomanov 没错,我赶紧回答,写了一个童话:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-07
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 2020-03-08
    相关资源
    最近更新 更多