Skip to content

Instantly share code, notes, and snippets.

@igstan
Last active June 15, 2017 22:50
Show Gist options
  • Save igstan/5620335 to your computer and use it in GitHub Desktop.
Save igstan/5620335 to your computer and use it in GitHub Desktop.
Polymorphic return types in Scala using implicit parameters
trait Factory[T] {
def create: T
}
object Factory {
implicit def stringFactory: Factory[String] = new Factory[String] {
def create = "foo"
}
implicit def intFactory: Factory[Int] = new Factory[Int] {
def create = 1
}
}
object Main {
def create[T](implicit factory: Factory[T]): T = factory.create
// or using a context bound
// def create[T : Factory]: T = implicitly[Factory[T]].create
def main(args: Array[String]): Unit = {
val s = create[String]
val i = create[Int]
println(s) // "foo"
println(i) // 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment