如何在自定义类中实现map/flatmap

Sim*_*ins 1 scala

我有一个名为Expect的类,在您实例化之后,您可以构建一个数据结构(为简单起见,可以说它是一棵树).然后调用遍历树的run方法,在每个节点上执行某些操作.这些操作需要一些时间才能完成,因此将来会返回最终结果.在伪代码中它将是这样的:

class Expect[R](command: String) {
  //some methods to build the tree

  def run()(implicit ec: ExecutionContext): Future[R] = {
    //Traverse the tree and execute actions on the nodes that eventually return a R
  }
}
Run Code Online (Sandbox Code Playgroud)

我想用他们常用的签名来实现map和flatmap,但是他们作为参数接收的函数必须在将来返回的值上运行.我看不出任何实现这一点的方法.

def map[T](f: R => T): Expect[T]
def flatMap[T](f: R => Expect[T]): Expect[T]
Run Code Online (Sandbox Code Playgroud)

ste*_*tew 5

以下类型引导我:

import scala.concurrent.{ExecutionContext, Future}

abstract class Expect[R](command: String) { self => 
  //some methods to build the tree

  def run(implicit ec: ExecutionContext): Future[R]

  def map[T](f: R => T): Expect[T] = new Expect[T](command) {
    def run(implicit ec: ExecutionContext): Future[T] =
      self.run.map(f)
  }

  def flatMap[T](f: R => Expect[T]): Expect[T] = new Expect[T](command) {
    def run(implicit ec: ExecutionContext): Future[T] =
      self.run.flatMap(r => f(r).run)
  }
}
Run Code Online (Sandbox Code Playgroud)

我认为这command可能不属于构造函数,它可能只需要通过实际使用command字符串的结构细化来关闭