public
Created

Attempt to simplify function composition from multiple partials using shapeless...

  • Download Gist
PartialShapeless.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
 
import shapeless._
import HList._
import Record._
 
object Shapeless {
type MyFunction = PartialFunction[Any, String]
 
object behaviourA extends Field[MyFunction] { override def toString = "BehaviourA" }
object behaviourB extends Field[MyFunction] { override def toString = "BehaviourB" }
object behaviourC extends Field[MyFunction] { override def toString = "BehaviourC" }
 
case object MessageA
case object MessageB
case object MessageC
 
def behaviourAType1: MyFunction = { case MessageA => "behaviourA type 1" }
def behaviourAType2: MyFunction = { case MessageA => "behaviourA type 2" }
def behaviourBType1: MyFunction = { case MessageB => "behaviourB type 1" }
def behaviourBType2: MyFunction = { case MessageB => "behaviourB type 2" }
def behaviourCType1: MyFunction = { case MessageC => "behaviourC type 1" }
def behaviourCType2: MyFunction = { case MessageC => "behaviourC type 2" }
 
var function = (behaviourA -> behaviourAType1) ::
(behaviourB -> behaviourBType1) ::
(behaviourC -> behaviourCType1) :: HNil
def func = function.get(behaviourA) orElse function.get(behaviourB) orElse function.get(behaviourC)
def runfunc() {
println("[MessageA]: " + func(MessageA))
println("[MessageB]: " + func(MessageB))
println("[MessageC]: " + func(MessageC))
}
def main(args: Array[String]) {
println("Run 1")
runfunc()
println("Run 2")
function = function + (behaviourA -> behaviourAType2)
runfunc()
println("Run 3")
function = function + (behaviourB -> behaviourBType2)
runfunc()
println("Run 4")
function = function + (behaviourC -> behaviourCType2)
runfunc()
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.