Skip to content

Instantly share code, notes, and snippets.

@carymrobbins
Last active August 29, 2015 14:14
Show Gist options
  • Save carymrobbins/8598f7eeaae5e2fc709e to your computer and use it in GitHub Desktop.
Save carymrobbins/8598f7eeaae5e2fc709e to your computer and use it in GitHub Desktop.
Use multiple values of the same base type as implicits with different contexts by separating them at the type level.
object Main {
def main(args: Array[String]) = {
implicit val pg = PostgreSQLConnection(ConnectionImpl("pg"))
implicit val mysql = MySQLConnection(ConnectionImpl("mysql"))
println(queryPostgreSQL("foo")) // prints "selected foo from pg"
println(queryMySQL("bar")) // prints "selected bar from mysql"
}
def queryPostgreSQL(x: String)(implicit pg: PostgreSQLConnection): String = pg { implicit c =>
doQuery(x)
}
def queryMySQL(x: String)(implicit mysql: MySQLConnection): String = mysql { implicit c =>
doQuery(x)
}
def doQuery(x: String)(implicit c: Connection): String = {
c.select(x)
}
}
trait Connection {
def select(x: String): String
}
case class ConnectionImpl(name: String) extends Connection {
def select(x: String) = s"selected $x from $name"
}
abstract class ProxyType[A](self: A) {
def apply[B](f: A => B) = f(self)
}
case class MySQLConnection(c: Connection) extends ProxyType(c)
case class PostgreSQLConnection(c: Connection) extends ProxyType(c)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment