I recently started to work on play & reactive mongo. Referred the reactive mongo documentation to create a SimpleAlbum. When I run the play app I am getting an error like "Implicit modifier cannot be used for top-level objects". Why am I getting this? Help me in resolving the issue. Thanks
package models
import org.joda.time.DateTime
import reactivemongo.bson._
case class SimpleAlbum(
title: String,
releaseYear: Int,
hiddenTrack: Option[String],
allMusicRating: Option[Double])
implicit object SimpleAlbumWriter extends BSONDocumentWriter[SimpleAlbum] {
def write(album: SimpleAlbum): BSONDocument = BSONDocument(
"title" -> album.title,
"releaseYear" -> album.releaseYear,
"hiddenTrack" -> album.hiddenTrack,
"allMusicRating" -> album.allMusicRating)
}
implicit object SimpleAlbumReader extends BSONDocumentReader[SimpleAlbum] {
def read(doc: BSONDocument): SimpleAlbum = {
SimpleAlbum(
doc.getAs[String]("title").get,
doc.getAs[Int]("releaseYear").get,
doc.getAs[String]("hiddenTrack"),
doc.getAs[Double]("allMusicRating"))
}
}
Scala 2.10 introduced a new feature called implicit classes. An implicit class is a class marked with the implicit keyword. This keyword makes the class's primary constructor available for implicit conversions when the class is in scope. Implicit classes were proposed in SIP-13.
In Scala, objects and values are treated mostly the same. An implicit object can be thought of as a value which is found in the process of looking up an implicit of its type.
With implicit request It allows to get an instance of Messages automatically (the compiler will implicitly call request2Messages(yourRequest) when needed but you need to have an implicit request (or request header) in scope.
implicit
cannot be used at the package level. You need to put your implicit objects inside another object that you can then import where you need the implicits, e.g.:
object MyImplicits {
implicit object SimpleAlbumWriter ....
implicit object SimpleAlbumReader ....
}
and then where you need access to the implicits just put
import MyImplicits._
as part of the package imports.
EDIT: As @m-z points out, using the package
object, you can and define implicits at the package level like this:
package models
package object Implicits {
implicit object SimpleAlbumWriter ....
implicit object SimpleAlbumReader ....
}
which imports in the same way:
import models.Implicits._
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With