我正在读取查询参数,并将其转换为Map[Symbol, String]
。我想通过一组案例类为这些查询参数添加一些类型安全性。
根据传入的http请求,这些案例类将有所不同,因此需要支持不同的案例类。
如果传入的查询参数与定义的case class
不匹配,则Parser
应该返回None
。
我尝试使用shapeless来实现通用解析器。如果所有参数均为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
}
}
答案 0 :(得分:4)
FromMap
使用shapeless.Typeable
将值转换为期望的类型。因此,使代码正常工作的最简单方法是定义Typeable
的实例,以将String
转换为Int
(对于任何值类型,还会出现另外的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
中使用这个新的typeclass:
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)
}