【问题标题】:What is the difference between Source[T, _] and Source[T, NotUsed]?Source[T, _] 和 Source[T, NotUsed] 有什么区别?
【发布时间】:2020-01-15 08:09:33
【问题描述】:

我有一个构建在 Play/Lagom 堆栈之上的应用程序。我需要调用一个需要Source[T, NotUsed] 的服务来将文件流式传输到它。这是服务的接口:

def foo(fooId: UUID): ServiceCall[Source[ByteString, NotUsed], Source[String, NotUsed]]

因此,我通过以下方式使用 Play 文档中的 Accumulator.source

  private def doSomething(fooId: UUID): BodyParser[Future[Seq[String]]] = BodyParser { _ =>
    Accumulator.source[ByteString]
      .mapFuture { source: Source[ByteString, NotUsed] =>
        externalService
          .foo(fooId)
          .invoke(source)
          .map { x =>
            Right(x.runWith(Sink.seq[String]))
          }
      }
  }

现在,在 mapFuture 调用中,source 的类型是 Source[ByteString, _],但如果我将其更改为 Source[ByteString, NotUsed] 以便调用服务,如上例所示,我会得到一个IDE 中的错误 Source[ByteString, _] 是预期的。 _ 不应该意味着我可以将类型更改为我想要的任何类型,包括NotUsed?另一方面,这两者在语义上不应该是等价的吗?我发现 Akka 团队引入了 akka.NotUsed 来替换 Unit,因为在某些以前的版本中物化值无关紧要,但这仍然没有给我提供如何解决我的问题的线索。

上面的sn-p类似于Play documentation on directing the body elsewhere.中的这个例子

【问题讨论】:

    标签: scala playframework akka covariance existential-type


    【解决方案1】:

    另一方面,这两者在语义上不应该是等价的吗 还是?

    没有。它们不等价,因为一个是另一个的子类型,反之则不然。

    Source[ByteString, NotUsed]Source[ByteString, _] 的子类型。因为Source 是协变的,所以Source[ByteString, _]Source[ByteString, Any] 相同。

    implicitly[Source[ByteString, NotUsed] <:< Source[ByteString, _]]
    implicitly[Source[ByteString, _] =:= Source[ByteString, Any]]
    implicitly[Source[ByteString, Any] =:= Source[ByteString, _]]
    

    Accumulator.source[ByteString]has typeAccumulator[ByteString, Source[ByteString, _]].mapFuture(..)acceptsSource[ByteString, _] =&gt; Future[B]。由于X =&gt; YY 中是协变的,但在X 中是逆变的Source[ByteString, _] =&gt; Future[B]Source[ByteString, NotUsed] =&gt; Future[B]) 的子类型

    implicitly[(Source[ByteString, _] => Future[B]) <:< (Source[ByteString, NotUsed] => Future[B])]
    

    因此您可以使用Source[ByteString, _] =&gt; Future[B] 代替Source[ByteString, NotUsed] =&gt; Future[B],但反之则不行。

    B 好像是Future[Either[Result, Future[Seq[String]]]]。)

    https://docs.scala-lang.org/tour/variances.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-10
      • 1970-01-01
      • 1970-01-01
      • 2012-11-27
      • 2021-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多