我正在查看cats.effect.concurrent.Deferred
并注意到其伴随对象中的所有纯工厂方法都返回,而F[Deferred[F, A]]
不仅仅是Deferred[F, A]
def apply[F[_], A](implicit F: Concurrent[F]): F[Deferred[F, A]] =
F.delay(unsafe[F, A])
但
/**
* Like `apply` but returns the newly allocated promise directly instead of wrapping it in `F.delay`.
* This method is considered unsafe because it is not referentially transparent -- it allocates
* mutable state.
*/
def unsafe[F[_]: Concurrent, A]: Deferred[F, A]
为什么?
定义了abstract class
两种方法(省略了文档):
abstract class Deferred[F[_], A] {
def get: F[A]
def complete(a: A): F[Unit]
}
因此,即使我们Deferred
直接分配,也不清楚如何Deferred
通过其公共方法修改状态。所有修改都用 暂停F[_]
。