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

时间:2013-03-07 10:49:25

标签: scala implicit traits

我希望一个对象实现特征Iterable并将另一个隐式参数传递给已实现的方法:

object MyRepository extends Iterable[Something] {

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

}

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

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

   def get = Action {
     Transaction { implicit EntityManager => 
       val result = MyRepository.map(s => s ...)
     }
   }

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

1 个答案:

答案 0 :(得分: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
}

当您执行MyRepository.map(...)时,现在发生的是对象被隐式转换为MyRepositoryIterable的实例,该实例捕获隐式EntityManager值。 MyRepositoryIterable是实际实现Iterable的类。