首页 > 解决方案 > 在scala中实现泛型方法的正确方法是什么

问题描述

我有这个数据源特征

trait DataSource {
  def insert[T](foo: Foo): Either[Exception, Future[T]]
}

然后我创建一个实现,如:

class MongoDataSource(collection: MongoCollection[Document]) extends DataSource {

  override def insert[ManagedObject](doc: ManagedObject): Either[Exception, Future[ManagedObject]] = {
    Right(Future(new ManagedObject("")))
  }
}

我得到错误:

class type required but ManagedObject found
    Right(Future(new ManagedObject("")))

标签: scalagenerics

解决方案


我想这可能是你想要的。

trait DataSource[T] {  //move type parameter to the trait
  def insert(foo: T): Either[Exception, Future[T]]
}

class MongoDataSource(collection: MongoCollection[Document]) extends DataSource[ManagedObject] {
  override def insert(doc: ManagedObject): Either[Exception, Future[ManagedObject]] = {
    Right(Future(new ManagedObject("")))
  }
}

推荐阅读