我正在尝试使用精致的来基于基元创建智能构造函数,并避免包装,因为在大型集合中可能使用相同的类型。我这样做对吗?似乎可以工作,但有点笨拙]
type ONE_Pred = = MatchesRegex[W....
type ONE = String @@ ONE_Pred
type TWO_Pred = OneOf[...
type TWO = String @@ TWO_PRED
然后
case class C(one:ONE, two:TWO)
object C {
def apply(one:String, two:String):Either[String, C] =
(
refineT[ONE_Pred](one),
refineT[TWO_Pred](two)
).mapN(C.apply)
}
Refined
具有一种用于创建类似伴侣的对象的机制,该对象具有已定义的一些实用程序:
type ONE = String @@ MatchesRegex["\\d+"]
object ONE extends RefinedTypeOps[ONE, String]
注意:
type ONE
的结构。您得到:
ONE("literal")
替代refineMT
/ refineMV
ONE.from(string)
替代refineT
/ refineV
ONE.unapply
,所以你可以做string match { case ONE(taggedValue) => ... }
ONE.unsafeFrom
,当您唯一的选择是引发异常时。有了这些“伴侣”,就可以编写简单得多的代码,而无需提及任何谓词类型:
object C {
def apply(one: String, two: String): Either[String, C] =
(ONE.from(one), TWO.from(two)).mapN(C.apply)
}
((scastie中的示例,将2.13与原始文字类型一起使用)