【问题标题】:What is the correct way to implement a generic method in scala在scala中实现泛型方法的正确方法是什么
【发布时间】:2021-03-12 05:29:59
【问题描述】:

我有这个数据源特征

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("")))

【问题讨论】:

  • ManagedObject,正如你在这里使用的,是一个类型参数。 (可能是Int。可能是Char....)因此,您不能通过new 实例化它。这不是 class 说明符。
  • trait 中的方法应该是:def insert[T](t: T): Either[Exception, Future[T]]?

标签: scala generics


【解决方案1】:

我想这可能是你想要的。

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("")))
  }
}

【讨论】:

  • 编译的工作,但这不是ai想要实现的。 DataSource 中的每个方法都将返回一个泛型类型。插入、删除、更新和获取的类型 T 不一样,所以我不能将该类型移动到类中。所以这种方法对我不起作用!
  • 如果您要为每个方法设置一个静态类型,您可以为每个方法设置一个单独的 trait(带有自己的类型参数),并将它们混合在一起以创建您的数据源
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-14
  • 1970-01-01
  • 2011-11-06
  • 2018-08-12
  • 1970-01-01
  • 1970-01-01
  • 2013-11-09
相关资源
最近更新 更多