我遇到了一个案例类+随播对象及其(可能)与Play交互的问题。每当我尝试将其作为方法的参数传递时,它都被解释为类型any
而不是EventList
。但是,在方法主体中使用它的效果很好。
我似乎不明白为什么。以下是所讨论代码的简化部分(来自大型代码库)。
EventList.scala:
package v1.objects
final case class EventList( ... ) {
...
}
object EventList {
def apply( ... ): EventList = {
...
new EventList( ... )
}
}
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
...
}
}
关于编译的错误消息:
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)
答案 0 :(得分:5)
这将创建任何列表:
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)