简体   繁体   English

使用akka-http时的问题,circe

[英]Issue when using akka-http, circe

Let's say I have this hierarchy:假设我有这个层次结构:

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")}

As you see I'm using akka http and circe, then I have the following:如您所见,我正在使用 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)
   }
}

But for some reason I can't use the method eat .但由于某种原因,我不能使用方法eat And I see that the type of transformed is immutable.Iterable[Result[_ >: Dog with Cat <: Animal]] I guess that's the problem that prevent me to call eat method.而且我看到转换的类型是不可transformedimmutable.Iterable[Result[_ >: Dog with Cat <: Animal]]我想这是阻止我调用eat方法的问题。

Is there anyway to fix that to be able to call the eat event?有没有办法解决这个问题以便能够调用eat事件?

As you noticed, the value you are getting is:正如您所注意到的,您获得的价值是:

Iterable[Result[_ >: Dog with Cat <: Animal with Product]]

while:尽管:

final type Result[A] = Either[DecodingFailure, A]

In order to access the eat method, you have to do:为了访问eat方法,您必须执行以下操作:

transformed.foreach(_.map(_.eat))

From you point of view, every time when map key is dog, its value is Dog class, but from compiler doesn't know about that.从您的角度来看,每次 map 键为 dog 时,其值为Dog class,但编译器并不知道这一点。

That is why transformed is Iterable[Result[X]] , and when traversing iterable you are trying to call eat method on Result type.这就是为什么转换的是Iterable[Result[X]] ,并且在遍历 iterable 时,您试图在Result类型上调用 eat 方法。

You have to extract value from Result object, only if it was deserialized correctly您必须从Result object 中提取值,前提是它已正确反序列化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM