1

I have a trait Document[T], and two case classes which extend that trait:

Memo(...) extends Document[Memo]
Fax(...) extends Document[Fax]

Each represents a different type of text file.

I want to clean these documents using some text tools, but creating a method that takes both types has vexed me.

val rawText: Seq[String]
// The text of all documents where one string in the sequence is the text of one document

val documentType = "Memo"
// Can also be "Fax"

val documentObjects = documentType match {
case "Memo" => rawText.map(_.makeMemoDocument) // results in Seq[Memo]
case "Fax" => rawText.map(_.makeFaxDocument) // results in Seq[Fax]
}

// Here lies my dilemma...
def processDocuments(docs: Seq[Document[T]]): Seq[Document[T]] = {...}

val processedDocs = processDocuments(documentObjects)

I want to define documentObjects in a way so that it can be easily accepted by processDocuments, i.e. processDocuments should accept either a Seq[Memo] or a Seq[Fax] as an argument.

I am creating case classes to be run through a Stanford CoreNLP pipeline, and I want to be able to support adding multiple case classes extending the Document[T] trait in the future (e.g. later on, add support for Pamphlet(...) extends Document[Pamphlet]).

Any help would be appreciated. If you require more information, I'd be happy to provide it.

1
  • 1
    Are your sure you need F-Bounded Polymorphism, I mean, do you really need your document to extend itself, like in class Memo(...) extends Document[Memo]? - Anyways, if yes, you can write your method like def processDocuments[T <: Document[T]](docs: Seq[T]): Seq[T] Commented May 17, 2019 at 19:20

1 Answer 1

1
val documentObjects:Document[_] = documentType match {
   case "Memo" => rawText.map(_.makeMemoDocument) // results in Seq[Memo]
   case "Fax" => rawText.map(_.makeFaxDocument) // results in Seq[Fax]
}

def processDocuments[T](docs: Seq[Document[T]]): Seq[Document[T]] = ???
val processedDocs = processDocuments(Seq(documentObjects))

or remove type declaration on documentObjects and use

def processDocuments(docs: Seq[Document[_]]): Seq[Document[_]] = ???
//or
def processDocuments[T <: Document[_]](docs: Seq[T]): Seq[T]= ???
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.