Created
September 16, 2018 22:06
-
-
Save abdheshkumar/a429fff56638b534abdd2c4e4d9cf1f9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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