使用 akka-http 时出现问题,circe
Issue when using akka-http, circe
假设我有这个层次结构:
sealed trait Animal {
def eat = println("eating!")
}
final case class Dog(name :String) extends Animal {override def eat= println("dog eating")}
final case class Cat(name: String) extends Animal {override def eat= println("cat eating")}
如你所见,我正在使用 akka http 和 circe,那么我有以下内容:
import io.circe.syntax._
import io.circe.Json
...
pathPrefix("path" / "something") {
post {
entityAs[Map[String,Json]] { data =>
// depending on the key of the map I will create an object Dog or Animal
val transformed = data.map { d =>
d._1 match {
case "dog" => d._2.as[Dog]
case "cat" => d._2.as[Cat]
}
}
// then I will do something like
transformed.foreach(_.eat)
complete(Status.OK)
}
}
但由于某些原因我无法使用 eat
方法。
我看到 transformed
的类型是 immutable.Iterable[Result[_ >: Dog with Cat <: Animal]]
我想这就是阻止我调用 eat
方法的问题。
有没有办法解决这个问题以便能够调用 eat
事件?
从你的角度来看,每次映射键是 dog 时,它的值是 Dog
class,但编译器不知道。
这就是为什么 transformed 是 Iterable[Result[X]]
,并且在遍历 iterable 时你试图调用 Result
类型的 eat 方法。
您必须从 Result
对象中提取值,前提是它被正确反序列化
如您所见,您得到的值是:
Iterable[Result[_ >: Dog with Cat <: Animal with Product]]
同时:
final type Result[A] = Either[DecodingFailure, A]
为了访问 eat
方法,您必须:
transformed.foreach(_.map(_.eat))
假设我有这个层次结构:
sealed trait Animal {
def eat = println("eating!")
}
final case class Dog(name :String) extends Animal {override def eat= println("dog eating")}
final case class Cat(name: String) extends Animal {override def eat= println("cat eating")}
如你所见,我正在使用 akka http 和 circe,那么我有以下内容:
import io.circe.syntax._
import io.circe.Json
...
pathPrefix("path" / "something") {
post {
entityAs[Map[String,Json]] { data =>
// depending on the key of the map I will create an object Dog or Animal
val transformed = data.map { d =>
d._1 match {
case "dog" => d._2.as[Dog]
case "cat" => d._2.as[Cat]
}
}
// then I will do something like
transformed.foreach(_.eat)
complete(Status.OK)
}
}
但由于某些原因我无法使用 eat
方法。
我看到 transformed
的类型是 immutable.Iterable[Result[_ >: Dog with Cat <: Animal]]
我想这就是阻止我调用 eat
方法的问题。
有没有办法解决这个问题以便能够调用 eat
事件?
从你的角度来看,每次映射键是 dog 时,它的值是 Dog
class,但编译器不知道。
这就是为什么 transformed 是 Iterable[Result[X]]
,并且在遍历 iterable 时你试图调用 Result
类型的 eat 方法。
您必须从 Result
对象中提取值,前提是它被正确反序列化
如您所见,您得到的值是:
Iterable[Result[_ >: Dog with Cat <: Animal with Product]]
同时:
final type Result[A] = Either[DecodingFailure, A]
为了访问 eat
方法,您必须:
transformed.foreach(_.map(_.eat))