Reputation: 25
I'm having trouble getting this implicit conversion to work properly. I keep getting these errors:
[error]
found: (scala.collection.immutable.Map[O,scala.collection.immutable.Seq[D]], O) => scala.collection.immutable.Map[O,scala.collection.immutable.Seq[D]]
required:
(Object, Object) => Object
at (operToDocsMap: Map[O, Seq[D]], operator: O) =>
[error] type mismatch;
found : Object
required: scala.collection.immutable.Map[O,scala.collection.immutable.Seq[D]]
at .fold(operatorToDocsMap){
My code:
object ModelTypes {
trait Document
trait DocumentOperator {
def operatesOn[D <: Document](document: D): Boolean
}
class Documents[D <: Document](docs: Seq[D]) {
def groupByOperator[O <: DocumentOperator](operators: Seq[O])
: Map[O, Seq[D]] = {
docs.foldLeft(Map[O, Seq[D]]()) {
(operatorToDocsMap: Map[O, Seq[D]], document: D) =>
operators
.filter(_.operatesOn(document))
.fold(operatorToDocsMap){
(operToDocsMap: Map[O, Seq[D]], operator: O) =>
{operToDocsMap + (operator -> (document +: operToDocsMap.getOrElse(operator, Seq())))}
}
}
}
}
implicit def documentsConverter[D <: Document](docs: Seq[D]) =
new Documents(docs)
}
Is it something wrong with the type bounds? Any help is greatly appreciated.
Upvotes: 0
Views: 88
Reputation: 11577
Below is more idiomatic way to achieve your requirement. This logic should give you the grouping between operators and documents without the use of convoluted nested foldJoins.
class Documents[D <: Document](docs: Seq[D]) {
def groupByOperator[O <: DocumentOperator](operators: Seq[O]): Map[O, Seq[D]] = {
val operatorDoc =
for {
doc <- docs
operator <- operators if operator.operatesOn(doc)
} yield (operator -> doc)
operatorDoc
.groupBy({ case (x, _) => x })
.mapValues(_.map({ case (_, x) => x }))
}
}
Upvotes: 1