在我的 Play + Reactive Mongo 应用程序中,我得到 Future[Option[Student]] 结果并且我正在尝试匹配结果:
def getStudent(id: String)=Action {
val futureOfStudent:Future[Option[Student]] = StudentRepository.getStudentById(id)
val timeoutFuture = play.api.libs.concurrent.Promise.timeout(0, Duration(3000, MILLISECONDS))
Async {
Future.firstCompletedOf(Seq(futureOfStudent, timeoutFuture)).map {
case s: Option[Student] => {s match {case Some(s)=>Ok(Json.toJson(s))
case None => NoContent}}
case i: Int => InternalServerError("Oooppppps!!!")
}
}
}
一切都像魅力一样工作,但我在 case s: Option[Student] =>
- non-variable type argument model.Student in type pattern
Option[modelStudent] is unchecked since it is eliminated by erasure
如何解决这个警告?
我用谷歌搜索了一下,找到了一些文章:
How do I get around type erasure on Scala? Or, why can't I get the type parameter of my collections?
Why does Scala warn about type erasure in the first case but not the second?
但是,它并没有告诉我如何作为 Play Controller 的一部分来解决。
请帮忙。
最佳答案
类型删除的问题是您不能再使用类型参数:Option[Student]
在运行时看起来就像 Option[_]
。这会导致以下问题:
val opt: Option[Student] = Some(myStudent)
opt match {
case s: Option[String] => println('problem') // this would happen
case s: Option[Student] => // this wouldn't get called
}
解决问题的最简单方法可能是……
case s: Option[_] => s match {
case Some(student: Student) => Ok(Json.toJson(student))
case _ => NoContent
}
但这并不能真正解决问题的根源。您创建的 Seq
包含一个 Future[Option[Student]]
和一个 Future[Int]
,因此它可能解析为一个 Seq[Future[Any]]
(Option[Student]
和 Int
之间最常见的类型),因此您的匹配项必须假定该项目是Any
类型,这实际上消除了此处类型检查器的用处。
您应该调整 Seq
以使其具有更好的通用类型。如果您使用 Option[Student]
作为超时 future 的返回类型,它可能会返回 None
,而 Seq
将是一个 Seq[ future [选项[学生]]]
。然后 map
可以假定您正在匹配 Option[Student]
。
关于mongodb - Play 框架应用程序中的 Scala 类型删除警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20577966/