在使用精炼

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

    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)
}
Godbobo 回答:在使用精炼

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与本机文字类型一起使用)

本文链接:https://www.f2er.com/3141881.html

大家都在问