代码之家  ›  专栏  ›  技术社区  ›  Kristian Rafael Alvarez

方法声明中的case类(带有伴生对象)被评估为any

  •  1
  • Kristian Rafael Alvarez  · 技术社区  · 6 年前

    我对case类+伴生对象和(可能)它与play的交互有问题。每当我试图将它作为方法的参数传递时,它被解释为 any 而不是 EventList . 然而,在方法体中使用它是完美的。

    我似乎不明白为什么。下面是所讨论的代码的简化部分(它来自于大型代码库)。

    事件列表.scala:

    package v1.objects
    
    final case class EventList( ... ) {
       ...
    }
    
    object EventList {
      def apply( ... ): EventList = {
        ...
        new EventList( ... )
      }
    }
    

    对象存储库.scala:

    package v1.objects
    
    class ObjectExecutionContext @Inject()(actorSystem: ActorSystem) extends CustomExecutionContext(actorSystem, "repository.dispatcher")
    
    trait ObjectRepository {
      def patch(newEvents: EventList)(implicit mc: MarkerContext): Future[Int]
      ...
    }
    
    @Singleton
    class ObjectRepositoryImpl @Inject()()(implicit ec: ObjectExecutionContext) extends ObjectRepository {
      override def patch(newEvents: EventList)(implicit mc: MarkerContext): Future[Int] = {
        ...
        var eventList = EventList(...) // Retreive the old events from DB, works fine
        eventList = EventList(eventList.underlying :+ newEvents.underlying) // <- This fails! newEvents has type Any
        ...
      }
    }
    

    编译时的错误消息:

    Error: overloaded method value apply with alternatives:
    (underlying: List[v1.objects.Event])v1.objects.EventList 
    <and>
    (doc: org.mongodb.scala.Document)v1.objects.EventList
    cannot be applied to (String, List[Object])
    eventList = EventList(eventList.underlying :+ newEvents.underlying)
    
    1 回复  |  直到 6 年前
        1
  •  5
  •   pme    6 年前

    这将创建一个列表,其中包括:

    eventList.underlying :+ newEvents.underlying
    

    这会将列表作为元素添加到现有列表中。

    和共同的 Super-Type 然后是 Any .

    您需要的是将列表添加到另一个列表的函数>这将返回其内容的列表:

    eventList.underlying ++ newEvents.underlying
    

    确切的语法取决于 underlying 类型。

    例子:

    case class EventList(underlying: Seq[String]) 
    
    val el1 = EventList(Seq("e1", "e2"))
    val el2 = EventList(Seq("e4", "e5"))
    
    println(el1.underlying :+ el2.underlying) // List(e1, e2, List(e4, e5))
    
    println(el1.underlying ++ el2.underlying) // List(e1, e2, e4, e5)