【问题标题】:Issue when using akka-http, circe使用akka-http时的问题,circe
【发布时间】:2021-05-12 11:14:09
【问题描述】:

假设我有这个层次结构:

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 事件?

【问题讨论】:

    标签: scala akka-http circe


    【解决方案1】:

    从你的角度来看,每次映射键为狗时,其值为Dog类,但编译器不知道这一点。

    这就是为什么transformed是Iterable[Result[X]],当遍历可迭代对象时,你试图在Result类型上调用eat方法。

    您必须从 Result 对象中提取值,前提是它被正确反序列化

    【讨论】:

      【解决方案2】:

      如您所见,您得到的价值是:

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

      同时:

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

      要访问eat 方法,您必须执行以下操作:

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

      【讨论】:

        猜你喜欢
        • 2021-06-21
        • 2019-07-01
        • 2017-10-03
        • 1970-01-01
        • 1970-01-01
        • 2018-02-06
        • 2020-05-10
        • 2019-11-03
        • 1970-01-01
        相关资源
        最近更新 更多