mahdix
5/21/2013 - 2:42 PM

Polymorphic return types in Scala using implicit parameters

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
  }
}