Scala 无形类型映射[符号,字符串] 与案例类



我正在读取查询参数并将它们转换为Map[Symbol, String]。我想通过一组案例类为这些查询参数添加一些类型安全性。

这些案例类会根据传入的 http 请求而有所不同,因此这需要支持不同的案例类。

如果传入的查询参数与定义的case class不匹配,则Parser应返回None

我尝试使用无形来实现通用解析器。如果所有参数都属于String类型,则它有效。但是我需要支持任何类型的查询参数。

我试图合并这篇文章中看到的隐式转换逻辑,但无法让它工作。 https://meta.plasm.us/posts/2015/11/08/type-classes-and-generic-derivation/(无形新手)

现有Parser(无字符串到类型转换):

class Parser[A] {
def from[R <: HList]
(m: Map[Symbol, String])
(implicit
gen: LabelledGeneric.Aux[A, R],
fromMap: FromMap[R]
): Option[A] = fromMap(m).map(gen.from)
}
object Parser {
def to[A]: Parser[A] = new Parser[A]
}

描述问题的测试:

class ParserSpec extends FlatSpec with Matchers {
private val sampleName: String = "Bob"
private val sampleVersion: Int = 1
//Partial Solution
case class QueryParams(name: String, version: String)
//Full Solution (not working)
case class QueryParams2(name: String, version: Int)
"A Parser" should "parse query parameters from a map with only string values" in {
val mapOfQueryParams = Map('name -> sampleName, 'version -> sampleVersion.toString)
val result = Parser.to[QueryParams].from(mapOfQueryParams)
result shouldBe 'defined
result.get.name shouldEqual sampleName
result.get.version shouldEqual sampleVersion.toString
}
it should "parse query parameters from a map with any type of value" in {
val mapOfQueryParams = Map('name -> sampleName, 'version -> sampleVersion.toString)
val result = Parser.to[QueryParams2].from(mapOfQueryParams)
//result is not defined as it's not able to convert a string to integer
result shouldBe 'defined
result.get.name shouldEqual sampleName
result.get.version shouldEqual sampleVersion
}
}

FromMap使用shapeless.Typeable将值转换为预期类型。因此,使代码正常工作的最简单方法是定义要从String转换为IntTypeable实例(以及出现在案例类中的任何值类型的其他Typeable实例):

implicit val stringToInt: Typeable[Int] = new Typeable[Int] {
override def cast(t: Any): Option[Int] = t match {
case t: String => Try(t.toInt).toOption
case _ => Typeable.intTypeable.cast(t)
}
override def describe: String = "Int from String"
}

然而,这不是Typeable的预期用途,它旨在确认类型为Any的变量已经是预期类型的实例,而无需任何转换。换句话说,它旨在成为asInstanceOf的类型安全实现,也可以解决类型擦除问题。


为了正确起见,您可以定义自己的ReadFromMap类型类,该类型类使用您自己的Read类型类从String类型转换为预期类型。下面是Read类型类的简单实现(假设 Scala 2.12):

import scala.util.Try
trait Read[T] {
def apply(string: String): Option[T]
}
object Read {
implicit val readString: Read[String] = Some(_)
implicit val readInt: Read[Int] = s => Try(s.toInt).toOption
// Add more implicits for other types in your case classes
}

您可以复制和调整FromMap的实现以使用此Read类型类:

import shapeless._
import shapeless.labelled._
trait ReadFromMap[R <: HList] extends Serializable {
def apply(map: Map[Symbol, String]): Option[R]
}
object ReadFromMap {
implicit def hnil: ReadFromMap[HNil] = _ => Some(HNil)
implicit def hlist[K <: Symbol, V, T <: HList](implicit
keyWitness: Witness.Aux[K],
readValue: Read[V],
readRest: ReadFromMap[T]
): ReadFromMap[FieldType[K, V] :: T] = map => for {
value <- map.get(keyWitness.value)
converted <- readValue(value)
rest <- readRest(map)
} yield field[K](converted) :: rest
}

然后只需在Parser中使用这个新的类型类:

class Parser[A] {
def from[R <: HList]
(m: Map[Symbol, String])
(implicit
gen: LabelledGeneric.Aux[A, R],
fromMap: ReadFromMap[R]
): Option[A] = fromMap(m).map(gen.from)
}

最新更新