评估为Any的方法声明中的Case类(带伴随对象)

Kri*_*rez 1 scala playframework

我有一个案例类+伴侣对象的问题,并且(可能)它与Play的交互.每当我尝试将其作为方法的参数传递时,它被解释为类型any而不是EventList.但是,在方法体中使用它可以完美地工作.

我似乎无法理解为什么.下面是相关代码的简化部分(来自大型代码库).

EventList.scala:

package v1.objects

final case class EventList( ... ) {
   ...
}

object EventList {
  def apply( ... ): EventList = {
    ...
    new EventList( ... )
  }
}
Run Code Online (Sandbox Code Playgroud)

ObjectRepository.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
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

编译时的错误消息:

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)
Run Code Online (Sandbox Code Playgroud)

pme*_*pme 5

这会创建一个Any列表:

eventList.underlying :+ newEvents.underlying
Run Code Online (Sandbox Code Playgroud)

这会将List作为元素添加到现有List中.

和普通Super-Type然后Any.

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

eventList.underlying ++ newEvents.underlying
Run Code Online (Sandbox Code Playgroud)

确切的语法取决于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)
Run Code Online (Sandbox Code Playgroud)