我正在为某些应用程序编写一个小注册模块,并使用类型类来执行此操作。主要逻辑基于Spray路由:
val api = post {
path("register" / Rest) { rest =>
rest match {
case "user" => register[User]
// ... other cases
}
}
}
}
为了简化,我有以下用户数据类型:
case class User(id: String, email: String)
为了从 POST 请求中提取实体,我使用了 typeclass:
trait EntityExtractor[T] {
def extractFromRequest: Directive[T :: String :: HNil]
}
用户实现:
object User {
implicit val extractor = new EntityExtractor[User] {
def extractFromRequest: Directive[User :: String :: HNil] =
formFields('email, 'pass).hmap {
case email :: pass :: HNil =>
val id = UID.genId
User(id, email) :: pass :: HNil
}
}
}
问题出现在我使用 typeclass 指令的 register 方法中:
def register[T] =
extractEntity[T].apply { entity => // fails here
validateEntity(entity) {
completeRegistration(entity)
}
}
}
def extractEntity[T: EntityExtractor]: Directive[Entity[T] :: HNil] = {
implicitly[EntityExtractor[T]].extractFromRequest.hmap {
case entity :: pass :: HNil => Entity(entity, pass) :: HNil
}
}
它失败了,但有一个例外:could not find implicit value for evidence parameter of type EntityExtractor[T]
.
有没有办法在没有模式匹配的情况下通过反射(TypeTags 或 Manifest)来解决这个问题?