mongodb - Play 框架应用程序中的 Scala 类型删除警告

标签 mongodb scala playframework-2.0

在我的 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/

相关文章:

java - IntelliJ IDEA 13 给出关于不兼容类型的无效错误(Play 中的 Java-Scala-InterOp)

scala - 选择Jupyter/IPython的许多Spark/Scala内核中的哪一个?

scala spec2 我无法创建同时使用 must be_== 和 failure 的测试

scala - 使用测试配置玩 2.0 FakeApplication 设置

playframework-2.0 - 任何用于 Play 框架的 CMS?

mysql - SQL 或 NoSQL 的扩展和性能

javascript - ngresource 无法使用基于 oData 的 Rest Controller 正确过滤

java - 使用java从sqlserver将大数据导出到CSV

node.js - TypeError : db. collection.createIndex 不是快速项目搜索功能中的函数

java - Play Framework Global.java 中的多个过滤器