尝试在使用精炼时保持未包装的类型

问题描述 投票:1回答:1

我正在尝试使用精致的来基于基元创建智能构造函数,并避免包装,因为在大型集合中可能使用相同的类型。我这样做对吗?似乎可以工作,但有点笨拙]

    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)
}
scala shapeless refined
1个回答
2
投票

Refined具有一种用于创建类似伴侣的对象的机制,该对象具有已定义的一些实用程序:

type ONE = String @@ MatchesRegex["\\d+"]
object ONE extends RefinedTypeOps[ONE, String]

注意:

  1. 您不需要单独提及谓词类型
  2. 它既适用于无形标签,也适用于改进的新类型。您获得的风味基于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与原始文字类型一起使用)

© www.soinside.com 2019 - 2024. All rights reserved.