Skip to content

Instantly share code, notes, and snippets.

@granthenke
Created March 17, 2015 03:22
Show Gist options
  • Save granthenke/a26d36654a2671894e64 to your computer and use it in GitHub Desktop.
Save granthenke/a26d36654a2671894e64 to your computer and use it in GitHub Desktop.
Client Reuse
class Client(connection: String) {
println("New Client: " + connection)
}
object Client {
private val clients = new mutable.HashMap[String, Client]()
def apply(connection: String): Client = {
clients.getOrElse(connection, createClient(connection))
}
private def createClient(connection: String): Client = {
val client = new Client(connection)
clients.put(connection, client)
client
}
}
@MansurAshraf
Copy link

Ok so lazy val cant take param so your approach is fine. Another approach would be as follow. The only advantage of this approach is that Scala is taking care of synchronization. Your approach has a small threading issue and apply should really be synchronized

object env{
 object dev {
  lazy val client = new Client("dev connection string")
}
object prod{
 lazy val client = new Client("prod connection string")
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment