首先,convert
方法的输出必须是,或者( , , , , 等) 的Option[Output]
某些单子,以防无法将 的内容转换为( 的长度错误、解析s 或等时出错等。 )Output
Try
Either
scalaz.\/
scalaz.Validation
Seq[String]
Output
Seq
Int
Doubles
一个可能的实现shapeless
将有一个类型类转换String
为其参数类型,以及一个辅助类型类将一个HList
of转换为第一个类型类String
的HList
表示Output
。
这是一个示例实现:
import shapeless._
import shapeless.syntax.std.traversable._
import shapeless.ops.traversable._
trait Parse[Out] {
def apply(value: String): Option[Out]
}
object Parse {
implicit object convertToInt extends Parse[Int] {
def apply(value: String) = Try(value.toInt).toOption
}
implicit object convertToString extends Parse[String] {
def apply(value: String) = Some(value)
}
implicit object convertToDouble extends Parse[Double] {
def apply(value: String) = Try(value.toDouble).toOption
}
}
trait ParseAll[Out] {
type In <: HList
def apply(values: In): Option[Out]
}
object ParseAll {
type Aux[I, O] = ParseAll[O] { type In = I }
implicit object convertHNil extends ParseAll[HNil] {
type In = HNil
def apply(value: HNil) = Some(HNil)
}
implicit def convertHList[T, HO <: HList](implicit
cv: Parse[T],
cl: ParseAll[HO]
) = new ParseAll[T :: HO] {
type In = String :: cl.In
def apply(value: In) = value match {
case x :: xs => for {
t <- cv(x)
h0 <- cl(xs)
} yield t :: h0
}
}
}
trait Converter {
type Output
def convert[S <: HList, H <: HList](values: List[String])(implicit
gen: Generic.Aux[Output, H], // Compute HList representation `H` of Output
parse: ParseAll.Aux[S, H], // Generate parser of Hlist of String `S` to HList `H`
ft: FromTraversable[S] // Generate converter of `List[String]` to HList of Strings `S`
): Option[Output] =
values.toHList[S].flatMap(parse.apply).map(gen.from)
}
升级此实现以返回您选择的错误单子(或抛出异常)而不是返回很简单Option
以下是如何使用它:
scala> object ConverterISD extends Converter {
type Output = (Int, String, Double)
}
defined object ConverterISD
scala> ConverterISD.convert(List("1", "foo", "2.34"))
res0: Option[ConverterISD.Output] = Some((1,foo,2.34))
scala> ConverterISD.convert(List("1", "foo", "2.34", "5"))
res1: Option[ConverterISD.Output] = None
scala> ConverterISD.convert(List("1", "foo", "bar"))
res2: Option[ConverterISD.Output] = None
它也适用于案例类而不是元组:
scala> case class Model(i: Int, d: Double)
defined class Model
scala> object ConverterModel extends Converter {
type Output = Model
}
defined object ConverterModel
scala> ConverterModel.convert(List("1", "2.34"))
res0: Option[ConverterModel.Output] = Some(Model(1,2.34))
scala> ConverterModel.convert(List("1"))
res1: Option[ConverterModel.Output] = None
scala> ConverterModel.convert(List("1", "foo"))
res2: Option[ConverterModel.Output] = None