Created
April 7, 2016 16:51
-
-
Save JSantosP/4888479a06b6c7064199f41f85b0b867 to your computer and use it in GitHub Desktop.
Type class approach for polymorphic behavior
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
object TypeClassApproach extends App { | |
// The logic ... | |
trait StreamT[T]{ | |
def values: Stream[T] | |
} | |
object StreamT { | |
implicit def genTraversableToValues[T,C[_]](t: C[T])(implicit ev: C[T] => GenTraversable[T]) = new StreamT[T]{ | |
def values = t.toStream | |
} | |
implicit def tryToValues[T,C[_]](t: C[T])(implicit ev: C[T] => Try[T]) = new StreamT[T] { | |
def values = t.toOption.toStream | |
} | |
implicit def futureToValues[T,C[_]](t: C[T])(implicit ev: C[T] => Future[T], atMost: Duration = Duration.Inf) = new StreamT[T] { | |
def values = Try(Await.result(t,atMost)).toOption.toStream | |
} | |
} | |
// Let's try it! | |
import StreamT._ | |
import scala.concurrent.ExecutionContext.Implicits.global | |
case class User(name: String, age: Int) | |
val result = for { | |
v1 <- List(1,2,3).values | |
v2 <- Set("hi","bye").values | |
v3 <- Option(true).values | |
v4 <- Try(2.0).values | |
v5 <- Future(User("john",15)).values | |
} yield (v1,v2,v3,v4,v5) | |
result.foreach(println) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment