-1

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("")))
jwvh
  • 46,953
  • 7
  • 29
  • 59
Jorge
  • 238
  • 1
  • 10
  • 2
    `ManagedObject`, as you're using it here, is a type parameter. (It might be `Int`. It might be `Char`....) As such you can't instantiate it via `new`. It's not a `class` specifier. – jwvh Mar 12 '21 at 05:50
  • 1
    Should the method in the trait be: `def insert[T](t: T): Either[Exception, Future[T]]`? – Tomer Shetah Mar 14 '21 at 08:14
  • https://stackoverflow.com/questions/1305563/how-to-instantiate-an-instance-of-type-represented-by-type-parameter-in-scala – Dmytro Mitin Mar 14 '21 at 17:48

1 Answers1

1

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("")))
  }
}
jwvh
  • 46,953
  • 7
  • 29
  • 59
  • That work for compilation, but that is not what ai want to achieve. Each method inside DataSource is goin to return a generic type. The type T is not the same for insert, delete, update and get, so I can't move that type to the class. So This approach doesn't work for me! – Jorge Mar 12 '21 at 13:42
  • If you're going to have a static type for each method, you could have a separate trait (with its own type parameter) for each method, and mix them together to make your DataSource – mbbush Mar 12 '21 at 22:05