简体   繁体   中英

Scala : Define implicit functions in an object or in a class

I am learning Play2 framework and start using implicit functions. I am converting some Position object to Json :

implicit val locationWrites = new Writes[Position] {
    def writes(position: Position) = Json.obj(
      "lat" -> position.lat,
      "lon" -> position.lon
    )
}

Should I do :

object JsonConversion {
  implicit val locationWrites = new Writes[Position] {
    def writes(position: Position) = Json.obj(
      "lat" -> position.lat,
      "lon" -> position.lon
    )
  }
}

or should I do :

class JsonConversion {
  implicit val locationWrites = new Writes[Position] {
    def writes(position: Position) = Json.obj(
      "lat" -> position.lat,
      "lon" -> position.lon
    )
  }
}

And then import this class or object where these implicit functions will be used.

What is the underlying difference in terms of instances and scalability of such implicit functions, for instance if they are to be called in a concurrent manner ?

Neither really. There is a much cleaner way to keep all your domain together and something people usually tend to forget. You can put implict in the companion object

Here's where you should really put them:

class Position { ... }
object Position {
  implicit val positionWrites = new Writes[Position] {
    def writes(position: Position) = Json.obj(
    "lat" -> position.lat,
    "lon" -> position.lon
    )
  }
}

By default, implicit resolution will look into the companion object. This prevents the domain from being scattered and there will be no weird files full of JSON formats. You can keep things coupled in the right places and it's easy to know where stuff needs to change if you update your classes.

On a side note, Play has more advanced JSON format generation using some fun macros. You can use Json.format[Type] or Json.writes[Type] or just Json.reads[Type] to simply generate the format you need with no manual effort.

implicit val positionFormat = Json.format[Position]

Just put your implicit method in an object and import it in this way:

import JsonConversion._

From performance point of view you should not have any concerns, since many calls could be executed with no side effect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM