Last active
June 15, 2017 22:50
-
-
Save igstan/5620335 to your computer and use it in GitHub Desktop.
Polymorphic return types in Scala using implicit parameters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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