【问题标题】:Play ReactiveMongo: Need to create generic result class for RawCommand using ReactiveMongo玩 ReactiveMongo:需要使用 ReactiveMongo 为 RawCommand 创建通用结果类
【发布时间】:2015-10-09 07:56:27
【问题描述】:

我想使用响应式 mongo 和 play 框架为 RawCommand 创建通用结果模型。但我有一个错误。以下是我的通用模型案例类结构。

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]];
}   

implicit val distinctRawCommandReader: BSONDocumentReader[DistinctRawCommandResult[T]] = Macros.reader[DistinctRawCommandResult[T]] 行生成错误:◾not found: type T 因为DistinctRawCommandResult 带参数。但是当我使用object DistinctRawCommandResultBsonFormatter[T] 时,这也会产生错误。

我如何为RawCommand 创建通用结果模型。

【问题讨论】:

标签: mongodb scala reactive-programming playframework-2.3 reactivemongo


【解决方案1】:

首先,如果类 val 修饰符是多余的(; 也在行尾)。

接下来,你不能用泛型类型定义一些值,所以 Scala 编译器在这一行生成错误not found: type T(真的,什么类型 T 传递到代码上的这一行?)

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

要使用多种类型的阅读器,请使用 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]
}

有关更多文档,请参阅 reactivemongo.bson.Macros.Options 对象。

【讨论】:

    猜你喜欢
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多