Skip to content

Instantly share code, notes, and snippets.

@renanreismartins
Created February 18, 2018 21:22
Show Gist options
  • Save renanreismartins/8c00a2d4e96cb4cff9ac7b9fa25dacfe to your computer and use it in GitHub Desktop.
Save renanreismartins/8c00a2d4e96cb4cff9ac7b9fa25dacfe to your computer and use it in GitHub Desktop.
List(1, 2, 3, 4, 5) match {
case (a1 @ 1) :: (a2 @ 2 ):: c :: _ => c
case List(a1 @ 1, a2 @ 2, c) => c
case _ => "no"
}
sealed trait State
case class WithOffer(offer: Offer) extends State
object WithOffer {
implicit val hasOffer: HasOffer[WithOffer] = new HasOffer[WithOffer] {
override def offer(s: WithOffer) = s.offer
}
}
case class WithoutOffer() extends State
case class WithPartner(partnerName: String) extends State
case class WithOfferAndPartner(offer: Offer, partnerName: String) extends State
object WithOfferAndPartner {
implicit val hasOffer: HasOffer[WithOfferAndPartner] = (s: WithOfferAndPartner) => s.offer
}
trait HasOffer[S] {
def offer(s: S): Offer
}
case class Offer(id: Int)
case class Merchant[S <: State](name: String, state: S) {
def addOfferBad(offer: Offer) = {
Merchant[WithOffer](name, WithOffer(offer))
}
def addOffer2(offer: Offer)(implicit ev: S =:= WithoutOffer) = {
Merchant[WithOffer](name, WithOffer(offer))
}
def getOfferSimple: Option[Offer] = ???
def getOfferEq(implicit ev: S =:= WithOffer): Offer = {
???
}
def getOffer(implicit ev: HasOffer[S]): Offer = {
ev.offer(state)
}
}
object Merchant {
// Bad, doesnt check current state of merchant
def withOffer(name: String, offer: Offer) = {
Merchant[WithOffer](name, WithOffer(offer))
}
def withoutOffer(name: String) = {
Merchant[WithoutOffer](name, WithoutOffer())
}
def addOffer(merchant: Merchant[WithoutOffer], offer: Offer) = Merchant[WithOffer](merchant.name, WithOffer(offer))
}
def printOffer(merchat: Merchant[WithOffer]) = {
println("offer: %s", merchat.state.offer)
}
//Merchant.withOffer("renan", Offer(1)).addOffer(Offer(1))
//Merchant.withOffer("renan", Offer(1)).addOffer2(Offer(1))
printOffer(Merchant.withOffer("renan", Offer(1)))
//printOffer(Merchant.withoutOffer("renan")) compile error
// Merchant[Int]("adam", 23)
Merchant.withOffer("renan", Offer(1)).getOffer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment