File tree Expand file tree Collapse file tree 3 files changed +34
-0
lines changed
main/scala/com/thoughtworks
test/scala/com/thoughtworks Expand file tree Collapse file tree 3 files changed +34
-0
lines changed Original file line number Diff line number Diff line change 11libraryDependencies += " org.scalatest" %%% " scalatest" % " 3.0.0" % Test
2+
3+ libraryDependencies += " com.chuusai" %%% " shapeless" % " 2.3.2"
Original file line number Diff line number Diff line change 11package com .thoughtworks
22
3+ import shapeless ._
4+ import shapeless .syntax .typeable ._
5+
36private [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}
Original file line number Diff line number Diff 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}
You can’t perform that action at this time.
0 commit comments