Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`implicit' modifier cannot be used for top-level objects

Tags:

scala

implicit

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"))
 }
}
like image 900
Kaushik Avatar asked Apr 30 '15 16:04

Kaushik


People also ask

What is the use of implicit class in Scala?

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.

What is implicit object in Scala?

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.

What is implicit request in Scala?

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.


1 Answers

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._
like image 116
Arne Claassen Avatar answered Sep 19 '22 14:09

Arne Claassen