Last active
May 31, 2016 06:17
-
-
Save cfchou/4fe4f3015e9e6d955c77ac587366c827 to your computer and use it in GitHub Desktop.
test implicits
This file contains 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
package types | |
import org.scalatest.{FlatSpec, Matchers} | |
// A couple of types which we can not modify | |
object ExistingTypes { | |
case class FrameA(id: Int, msg: String) | |
case class FrameB(id: Int, msg: String, property_b: String) | |
case class FrameC(id: Int, msg: String, property_c: Long) | |
} | |
object Wrapper { | |
import ExistingTypes._ | |
trait FrameType { | |
type Repr | |
val frame: Repr | |
val id: Int | |
} | |
implicit object FrameAOrdering extends Ordering[FrameA] { | |
override def compare(x: FrameA, y: FrameA): Int = { | |
x.id.compare(y.id) * -1 | |
} | |
} | |
implicit def A2FrameType(f: FrameA): FrameType = { | |
new FrameType { | |
type Repr = FrameA | |
val frame = f | |
val id = f.id | |
} | |
} | |
implicit def B2FrameType(f: FrameB): FrameType = { | |
new FrameType { | |
type Repr = FrameB | |
val frame = f | |
val id = f.id | |
} | |
} | |
implicit def C2FrameType(f: FrameC): FrameType = { | |
new FrameType { | |
type Repr = FrameC | |
val frame = f | |
val id = f.id | |
} | |
} | |
// 1. create a Vector[FrameType]() | |
// 2. insert a FrameA/FrameB to Vector[FrameType] | |
// 3. pop and then pattern match an element | |
def init(): Vector[FrameType] = { | |
Vector[FrameType]() | |
} | |
def insert[T](frame: T, frames: Seq[FrameType])(implicit ev: T => FrameType): Seq[FrameType] = { | |
frames :+ ev(frame) | |
} | |
def dequeue(frames: Seq[FrameType]): (Option[FrameType], Seq[FrameType]) = { | |
if (frames.length > 0) { | |
val h = frames.head | |
h.frame match { | |
case f@FrameA(id, msg) => println(s"FrameA ${f}") | |
case f@FrameB(id, msg, property_b) => println(s"FrameB ${f}") | |
case f@FrameC(id, msg, property_c) => println(s"FrameC ${f}") | |
case _ => | |
} | |
(Some(h), frames.tail) | |
} else { | |
(None, frames) | |
} | |
} | |
} | |
import ExistingTypes._ | |
import Wrapper._ | |
class TypesSpec extends FlatSpec with Matchers { | |
val test_frames = (FrameB(10, "B", "prop_b"), FrameC(5, "C", 5), FrameA(15, "A")) | |
val init_frames = init() | |
"dequeue" should "see the sequence that frames were inserted" in { | |
val fs1 = insert(test_frames._1, init_frames) | |
val fs2 = insert(test_frames._2, fs1) | |
val fs3 = insert(test_frames._3, fs2) | |
val (e1, t1) = dequeue(fs3) | |
assert(e1.get.frame === test_frames._1) | |
val (e2, t2) = dequeue(t1) | |
assert(e2.get.frame === test_frames._2) | |
val (e3, t3) = dequeue(t2) | |
assert(e3.get.frame === test_frames._3) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment