简体   繁体   English

在 scala 中实现泛型方法的正确方法是什么

[英]What is the correct way to implement a generic method in scala

I have this Datasource trait我有这个数据源特征

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

Then I create an implementation like:然后我创建一个实现,如:

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

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

I got error:我收到错误:

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

I think this might be what you want.我想这可能是你想要的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在scala中实现Producer Consumer的正确方法是什么 - What is the correct way to implement Producer Consumer in scala 在Scala中使用泛型实现特征的正确方法是什么? - What is the correct way to implement trait with generics in Scala? 在 main 上调用此 Scala 方法的正确方法是什么? - What is the correct way to invoke this Scala method on main? Scala,无法实现通用的Java方法 - Scala, can't implement generic java method 在Play Scala中实现Pk写入的通用方法 - Generic way to implement a Pk Writes in Play Scala 在scala中为递归类型指定泛型的正确方法 - correct way to specify generic for recursive type in scala 在akka-http Scala中将通用类型注册到spray-json-support的正确方法是什么? - What is the correct way to register generic type to spray-json-support in akka-http Scala? 在Scala中支持poll(n)功能的内存队列中实现的正确方法是什么? - What is correct way to implement in memory queue in Scala, that support poll(n) functionality? 什么是使用猫或其他方式在 scala 列表中实现具有 m 个子项的树数据结构的 Functor 的正确方法 - What is correct way to implement Functor for Tree data structure with m children in a list in scala using cats or otherwise Scala:计算标准偏差的通用方法是什么 - Scala: What is the generic way to calculate standard deviation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM