Skip to content

Instantly share code, notes, and snippets.

@abdheshkumar
Created September 16, 2018 22:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdheshkumar/a429fff56638b534abdd2c4e4d9cf1f9 to your computer and use it in GitHub Desktop.
Save abdheshkumar/a429fff56638b534abdd2c4e4d9cf1f9 to your computer and use it in GitHub Desktop.
//In library
trait Event
trait EventCombiner[A <: Event] {
def initialValue: Int
def combineEvents(value: Int, e2: A): Int
}
def foldEvents[A <: Event](list: Seq[A])(implicit C: EventCombiner[A]): Int =
list.foldLeft(C.initialValue)(C.combineEvents)
//Outside library
sealed trait HandledEvent extends Event with Product with Serializable
object HandledEvent {
implicit val handledEvent: EventCombiner[HandledEvent] = new EventCombiner[HandledEvent] {
override def initialValue: Int = 0
override def combineEvents(value: Int, e2: HandledEvent): Int = {
e2 match {
case Reset => 0
case Inc(i) => value + i
case Noop => value
}
}
}
}
case object Reset extends HandledEvent
case class Inc(by: Int) extends HandledEvent
case object Noop extends HandledEvent
private val events = Seq(Inc(5), Inc(2), Inc(3), Reset, Inc(2))
foldEvents(events)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment