0

I want to create generic result models for RawCommand using reactive mongo with play framework. But i got an error. Following is my generic models case class structure.

case class DistinctRawCommandResult[T] (

 val values: List[T],
 val stats: CommandStatus,
 val ok: Double
)

case class CommandStatus(

 val n: Int,
 val nscanned: Int,
 val nscannedObjects: Int,
 val timems: Int,
 val cursor: String
)

object DistinctRawCommandResultBsonFormatter {

 implicit val commandStatusReader: BSONDocumentReader[CommandStatus] = Macros.reader[CommandStatus];
 implicit val distinctRawCommandReader: BSONDocumentReader[DistinctRawCommandResult[T]] = Macros.reader[DistinctRawCommandResult[T]];
}   

At line implicit val distinctRawCommandReader: BSONDocumentReader[DistinctRawCommandResult[T]] = Macros.reader[DistinctRawCommandResult[T]] the error is generated: ◾not found: type T because DistinctRawCommandResult takes parameter. But when i use object DistinctRawCommandResultBsonFormatter[T], then this also generate an error.

How could i create generic result model for RawCommand.

Harmeet Singh Taara
  • 6,483
  • 20
  • 73
  • 126
  • A distinct command will be providedvin next release. Meanwhile you can code the code from master: https://github.com/ReactiveMongo/ReactiveMongo/pull/411 – cchantep Oct 14 '15 at 07:14

1 Answers1

0

First of all, in case class val modifier is redundant (and ; at the end of line too).

Next, you can't define some value with generic type, so Scala compiler generate the error not found: type T in this line (really, what type T pass to this line on code?)

implicit val distinctRawCommandReader: BSONDocumentReader[DistinctRawCommandResult[T]] = Macros.reader[DistinctRawCommandResult[T]];

To use readers with multiple types use Macros.handlerOps from import reactivemongo.bson.Macros.Options._

//define generic top trait (must be sealed)
sealed trait MyGenericType

//trait implementations. Driver saves classname field to database to know, what instance of class need to create. 
case class OneType(n: Int) extends MyGenericType
case class TwoType(s: String) extends MyGenericType

//and so on

case class DistinctRawCommandResult(values: List[MyGenericType],
                                    stats: CommandStatus,
                                    ok: Double)

case class CommandStatus(n: Int,
                         nscanned: Int,
                         nscannedObjects: Int,
                         timems: Int,
                         cursor: String)

object DistinctRawCommandResultBsonFormatter {
  implicit val commandStatusReader = Macros.reader[CommandStatus]

  // find all subtypes of MyGenericType
  implicit val distinctRawCommandReader = Macros.handlerOpts[MyGenericType,  AllImplementations]
}

For more documentation see reactivemongo.bson.Macros.Options object.

Łukasz
  • 8,555
  • 2
  • 28
  • 51
MrRontgen
  • 132
  • 1
  • 6