Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
sealed trait A
case class B[Req, Res](r: Req, rs: Res) extends A
case class C[Req](r: Req, errorCode: Int, errorMessage: String) extends A
trait TypeA[Req, Res] {
def success(t: Req, r: Res): Unit
def error(t: Req): Unit
}
implicit val forString = new TypeA[String, String] {
override def success(t: String, r: String): Unit = ???
override def error(t: String): Unit = ???
}
def success[Req, Res](r: Req, rs: Res)(implicit in: TypeA[Req, Res]) = in.success(r, rs)
def fail[Req, Res](r: Req)(implicit in: TypeA[Req, Res]) = in.error(r)
def run(a: A) = a match {
case B(r, rs) => success(r, rs)
case C(r, e, em) => fail(r)
}
/********************************************An Example for view sub-class typeclasses*************************************************/
// Start writing your ScalaFiddle code here
sealed trait Request
case class AuthRequest(a: String) extends Request
case class PartyRequest(a: Int) extends Request
sealed trait Token
case class TokenSuccess(r: Request) extends Token
case class TokenFailure(r: Request, errorCode: Int, errorMessage: String) extends Token
trait Log[Req] {
def success(t: Req): Unit
def error(t: Req): Unit
}
implicit val forString: Log[AuthRequest] = new Log[AuthRequest] {
override def success(t: AuthRequest): Unit = println(t)
override def error(t: AuthRequest): Unit = println(t)
}
implicit val partyReq: Log[PartyRequest] = new Log[PartyRequest] {
override def success(t: PartyRequest): Unit = println(t)
override def error(t: PartyRequest): Unit = println(t)
}
def success[Req](r: Req)(implicit evidence: Log[Req]): Unit = evidence.success(r)
def fail[Req](r: Req)(implicit evidence: Log[Req]): Unit = evidence.error(r)
def run(a: Token) = a match {
case TokenSuccess(r) => success(r)
case TokenFailure(r, e, em) => fail(r)
}
run(TokenSuccess(AuthRequest("This is Auth Request")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.