Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//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
You can’t perform that action at this time.