Created
March 14, 2018 16:28
-
-
Save pshirshov/ee0a30379f9b335508f0eb37ff8081fa to your computer and use it in GitHub Desktop.
A simple example explaning how to abstract on result container moand type
This file contains 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
import cats._ | |
import cats.implicits._ | |
trait Service[R[_]] { | |
type Result[T] = R[T] | |
def computeValue(): Result[Int] | |
} | |
class ServiceImpl[R[_] : Monad : Foldable] | |
( | |
) | |
extends Service[R] { | |
protected val RM: Monad[R] = implicitly[Monad[R]] | |
protected val RF: Foldable[R] = implicitly[Foldable[R]] | |
def computeValue(): Result[Int] = { | |
RM.pure { | |
1 | |
} | |
} | |
} | |
object Test { | |
type Res[R] = Id[R] | |
def main(args: Array[String]): Unit = { | |
{ | |
val service = new ServiceImpl[Id]() | |
val result = 1 + service.computeValue() // Int | |
println(result) // 2 | |
} | |
{ | |
import scala.util._ | |
val service = new ServiceImpl[Try]() | |
val result = service.computeValue().map(_ + 1) // Try[Int] | |
println(result) // Success(2) | |
} | |
} | |
} | |
Test.main(Array.empty) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment