[英]Scala and Play: how can I use my implicit object?
隐式参数应该很容易,但到目前为止还不是。
我一直在使用ReactiveMongo在我的Scala / Play 2.4应用程序中保存和检索数据。 一段时间以来,我一直在控制器中进行保存,但是我想将代码移动到要保存的实体的伴随对象中。 这就是麻烦开始的地方。
这里是我的控制器中的相关内容,展示的东西是怎么做的工作:
package controllers
...
import model.Destination
import model.Destination.DestinationBSONReader
import scala.concurrent.ExecutionContext.Implicits.global
...
def add = Action { implicit request =>
Destination.destinationForm().bindFromRequest.fold(
formWithErrors => {
implicit val helper = sfh(formWithErrors)
BadRequest(views.html.addDestination(formWithErrors))
},
destinationData => {
Destination.mongoCollection.insert(destinationData)
...
Redirect("/destinations").flashing("success" -> s"The destination ${destinationData.name} has been created")
}
}
)
}
您可以想象一个表单提交的数据填充了“目标”,然后将其保存到Mongo。 将导入目标对象,以及scala ExecutionContext。 我的“ Destination”伴随对象具有BSONDocumentWriter [Destination]的实例(mongoCollection.insert()调用暗含了此实例),如下所示:
object Destination {
...
implicit object DestinationBSONWriter extends BSONDocumentWriter[Destination] {
override def write(destination: Destination): BSONDocument = {
val dbId = if (destination.id.isDefined) { destination.id.get } else { BSONObjectID.generate.stringify }
destination.newId = dbId
BSONDocument(
"id" -> dbId,
... lots of other key/value pairs,
"name" -> destination.name)
}
}
...
}
现在,我想将mongoCollection.insert(destinationData)调用移至同一“ Destination”对象; 控制器确实不应该与数据存储区通信。 因此,我创建了一个简单的方法,无论做什么都会导致编译错误:
def create(destination: Destination) = {
Destination.mongoCollection.insert(destination)
}
^-编译失败; “找不到参数编写器的隐式值:reactmongo.bson.BSONDocumentWriter [model.Destination]”
所以我将导入添加到类的顶部,因为Scala编译器应该在搜索隐式时查看导入:
import model.Destination.DestinationBSONWriter
import scala.concurrent.ExecutionContext.Implicits.global
^-相同的编译错误
因此,我决定显式传递隐式参数:
def create(destination: Destination) = {
Destination.mongoCollection.insert(destination)(writer = DestinationBSONWriter, ec=global)
}
^-那导致编译器挂起,我需要重新启动激活器。
我很困惑。 该隐式参数就在同一对象中,但编译器未检测到它。 我应该如何使用它?
经过一天的研究,SBT显然存在问题。 无论出于什么原因,它决定在应该成功编译我的代码时挂起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.