使用其他隐式参数实现traits方法

dea*_*mon 6 scala implicit traits

我想要一个对象来实现trait Iterable并将另一个隐式参数传递给已实现的方法:

object MyRepository extends Iterable[Something] {

  def iterator(implict entityManager: EntityManager): Iterator[Something] = ...

}
Run Code Online (Sandbox Code Playgroud)

显然这不起作用,因为该iterator方法没有隐含参数,因此不能通过上面显示的方法实现.

示例用例是map我想要应用于存储库值的方法:

   def get = Action {
     Transaction { implicit EntityManager => 
       val result = MyRepository.map(s => s ...)
     }
   }
Run Code Online (Sandbox Code Playgroud)

有没有办法实现Iterable特征并捕获隐式pramameter?

Rég*_*les 9

鉴于Iterable.iterator它的签名没有隐含,你不能指望在添加这个隐式时能够实现这个方法:那将是另一种方法(特别是另一种重载).

但是,如果MyRepository是类而不是对象,则可以捕获类构造函数中的隐式.如果你想保持相同的使用方式(MyRepository.map{ ... }而不是new MyRepository.map{ ... }),你可以做的是提供从对象到类的隐式转换.

这是一个例子:

object MyRepository {  
  class MyRepositoryIterable(implicit entityManager: EntityManager) extends Iterable[Something] {
    def iterator: Iterator[Something] = ???
  }
  implicit def toIterable(rep: MyRepository.type)(implicit entityManager: EntityManager): MyRepositoryIterable = new MyRepositoryIterable
}
Run Code Online (Sandbox Code Playgroud)

现在发生的事情MyRepository.map(...)是,对象被隐式转换为MyRepositoryIterable捕获隐式EntityManager值的实例.这MyRepositoryIterable是实际实现的类Iterable.