Skip to content

Instantly share code, notes, and snippets.

@pshirshov
Created March 14, 2018 16:28
Show Gist options
  • Save pshirshov/ee0a30379f9b335508f0eb37ff8081fa to your computer and use it in GitHub Desktop.
Save pshirshov/ee0a30379f9b335508f0eb37ff8081fa to your computer and use it in GitHub Desktop.
A simple example explaning how to abstract on result container moand type
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