Skip to content

Commit d0c93fd

Browse files
committed
Add typecheck method
1 parent aeb0648 commit d0c93fd

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

shared/build.sbt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,3 @@
11
libraryDependencies += "org.scalatest" %%% "scalatest" % "3.0.0" % Test
2+
3+
libraryDependencies += "com.chuusai" %%% "shapeless" % "2.3.2"

shared/src/main/scala/com/thoughtworks/Extractor.scala

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package com.thoughtworks
22

3+
import shapeless._
4+
import shapeless.syntax.typeable._
5+
36
private[thoughtworks] sealed trait LowLowPriorityExtractor {
47

58
implicit final class FunctionToExtractor[-A, +B] private[LowLowPriorityExtractor] (underlying: A => B) {
@@ -101,4 +104,13 @@ object Extractor extends LowPriorityExtractor {
101104
}
102105
}
103106

107+
implicit final class OptionFunctionToTypeableExtractor[-A: Typeable, +B] private[Extractor] (
108+
underlying: A => Option[B]) {
109+
def typecheck = new Extractor[A, B] {
110+
override def unapply(a: A): Option[B] = {
111+
a.cast[A].flatMap(underlying)
112+
}
113+
}
114+
}
115+
104116
}

shared/src/test/scala/com/thoughtworks/ExtractorSpec.scala

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,4 +73,24 @@ class ExtractorSpec extends FreeSpec with Matchers {
7373
test(2) should be("matched by optional function")
7474
test(3) should be("Not matched")
7575
}
76+
77+
"type checking" in {
78+
val pairToString = { pair: (Seq[Int], List[String]) =>
79+
(pair._1 ++ pair._2).mkString
80+
}
81+
82+
def test(a: Any) = {
83+
a match {
84+
case pairToString.extract.typecheck(s) => s"strict $s"
85+
case pairToString.extract(s) => s
86+
case _ => "Not matched"
87+
}
88+
}
89+
90+
test((Nil, List("1"))) should be("strict 1")
91+
test((Seq("xxx"), List(3))) should be("xxx3")
92+
test(0.5) should be("Not matched")
93+
94+
}
95+
7696
}

0 commit comments

Comments
 (0)